use sea_orm_migration::{prelude::*, sea_query::Expr};

#[derive(DeriveMigrationName)]
pub struct Migration;

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

#[derive(DeriveIden)]
enum AudioTracks {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum AudioTags {
    Table,
    Id,
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.create_table(
            Table::create()
                .table(AudioTrackTags::Table)
                .if_not_exists()
                .col(ColumnDef::new(AudioTrackTags::TrackId).uuid().not_null())
                .col(ColumnDef::new(AudioTrackTags::TagId).uuid().not_null())
                .col(
                    ColumnDef::new(AudioTrackTags::CreatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .primary_key(
                    Index::create()
                        .name("pk-audio_track_tags")
                        .col(AudioTrackTags::TrackId)
                        .col(AudioTrackTags::TagId),
                )
                .foreign_key(
                    ForeignKey::create()
                        .name("fk-audio_track_tags-track_id-to-audio_tracks")
                        .from(AudioTrackTags::Table, AudioTrackTags::TrackId)
                        .to(AudioTracks::Table, AudioTracks::Id)
                        .on_delete(ForeignKeyAction::Cascade)
                        .on_update(ForeignKeyAction::Cascade),
                )
                .foreign_key(
                    ForeignKey::create()
                        .name("fk-audio_track_tags-tag_id-to-audio_tags")
                        .from(AudioTrackTags::Table, AudioTrackTags::TagId)
                        .to(AudioTags::Table, AudioTags::Id)
                        .on_delete(ForeignKeyAction::Cascade)
                        .on_update(ForeignKeyAction::Cascade),
                )
                .to_owned(),
        )
        .await?;
        Ok(())
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.drop_table(Table::drop().table(AudioTrackTags::Table).to_owned())
            .await?;
        Ok(())
    }
}
