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

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(DeriveIden)]
enum AudioAlbums {
    Table,
    Id,
    Title,
    Slug,
    Description,
    CoverImageId,
    Artist,
    ReleaseDate,
    Published,
    UploaderId,
    ViewCount,
    CreatedAt,
    UpdatedAt,
    PublishedAt,
}

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

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.create_table(
            Table::create()
                .table(AudioAlbums::Table)
                .if_not_exists()
                .col(
                    ColumnDef::new(AudioAlbums::Id)
                        .uuid()
                        .not_null()
                        .primary_key(),
                )
                .col(
                    ColumnDef::new(AudioAlbums::Title)
                        .string_len(500)
                        .not_null(),
                )
                .col(
                    ColumnDef::new(AudioAlbums::Slug)
                        .string_len(500)
                        .not_null()
                        .unique_key(),
                )
                .col(ColumnDef::new(AudioAlbums::Description).text().null())
                .col(
                    ColumnDef::new(AudioAlbums::CoverImageId)
                        .string_len(500)
                        .null(),
                )
                .col(ColumnDef::new(AudioAlbums::Artist).string_len(500).null())
                .col(ColumnDef::new(AudioAlbums::ReleaseDate).date().null())
                .col(
                    ColumnDef::new(AudioAlbums::Published)
                        .boolean()
                        .not_null()
                        .default(false),
                )
                .col(ColumnDef::new(AudioAlbums::UploaderId).integer().not_null())
                .col(
                    ColumnDef::new(AudioAlbums::ViewCount)
                        .integer()
                        .not_null()
                        .default(0),
                )
                .col(
                    ColumnDef::new(AudioAlbums::CreatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .col(
                    ColumnDef::new(AudioAlbums::UpdatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .col(
                    ColumnDef::new(AudioAlbums::PublishedAt)
                        .timestamp_with_time_zone()
                        .null(),
                )
                .foreign_key(
                    ForeignKey::create()
                        .name("fk-audio_albums-uploader_id-to-users")
                        .from(AudioAlbums::Table, AudioAlbums::UploaderId)
                        .to(Users::Table, Users::Id)
                        .on_delete(ForeignKeyAction::Cascade)
                        .on_update(ForeignKeyAction::Cascade),
                )
                .to_owned(),
        )
        .await?;

        create_index(m, "idx-audio_albums-slug", AudioAlbums::Slug).await?;
        create_index(m, "idx-audio_albums-published", AudioAlbums::Published).await?;
        create_index(m, "idx-audio_albums-uploader_id", AudioAlbums::UploaderId).await?;
        Ok(())
    }

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

async fn create_index<T>(m: &SchemaManager<'_>, name: &str, col: T) -> Result<(), DbErr>
where
    T: Iden + 'static,
{
    m.create_index(
        Index::create()
            .name(name)
            .table(AudioAlbums::Table)
            .col(col)
            .to_owned(),
    )
    .await
}
