use sea_orm_migration::{prelude::*, sea_orm::ConnectionTrait};

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(DeriveIden)]
enum AudioTrackTags {
    Table,
    TagId,
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        if matches!(
            m.get_database_backend(),
            sea_orm_migration::sea_orm::DatabaseBackend::Postgres
        ) {
            m.get_connection()
                .execute_unprepared(
                    "ALTER TABLE users \
                     ADD CONSTRAINT chk_users_theme \
                     CHECK (theme IN ('light', 'dark'))",
                )
                .await?;
        }

        m.create_index(
            Index::create()
                .name("idx-audio_track_tags-tag_id")
                .table(AudioTrackTags::Table)
                .col(AudioTrackTags::TagId)
                .to_owned(),
        )
        .await?;

        Ok(())
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.drop_index(
            Index::drop()
                .name("idx-audio_track_tags-tag_id")
                .table(AudioTrackTags::Table)
                .to_owned(),
        )
        .await?;

        if matches!(
            m.get_database_backend(),
            sea_orm_migration::sea_orm::DatabaseBackend::Postgres
        ) {
            m.get_connection()
                .execute_unprepared("ALTER TABLE users DROP CONSTRAINT chk_users_theme")
                .await?;
        }

        Ok(())
    }
}
