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

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(DeriveIden)]
enum BlogArticles {
    Table,
    Id,
    Title,
    Slug,
    Content,
    Excerpt,
    Published,
    AuthorId,
    FeaturedImageId,
    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(BlogArticles::Table)
                .if_not_exists()
                .col(
                    ColumnDef::new(BlogArticles::Id)
                        .uuid()
                        .not_null()
                        .primary_key(),
                )
                .col(
                    ColumnDef::new(BlogArticles::Title)
                        .string_len(500)
                        .not_null(),
                )
                .col(
                    ColumnDef::new(BlogArticles::Slug)
                        .string_len(500)
                        .not_null()
                        .unique_key(),
                )
                .col(ColumnDef::new(BlogArticles::Content).text().not_null())
                .col(
                    ColumnDef::new(BlogArticles::Excerpt)
                        .string_len(1000)
                        .null(),
                )
                .col(
                    ColumnDef::new(BlogArticles::Published)
                        .boolean()
                        .not_null()
                        .default(false),
                )
                .col(ColumnDef::new(BlogArticles::AuthorId).integer().not_null())
                .col(
                    ColumnDef::new(BlogArticles::FeaturedImageId)
                        .string_len(500)
                        .null(),
                )
                .col(
                    ColumnDef::new(BlogArticles::ViewCount)
                        .integer()
                        .not_null()
                        .default(0),
                )
                .col(
                    ColumnDef::new(BlogArticles::CreatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .col(
                    ColumnDef::new(BlogArticles::UpdatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .col(
                    ColumnDef::new(BlogArticles::PublishedAt)
                        .timestamp_with_time_zone()
                        .null(),
                )
                .foreign_key(
                    ForeignKey::create()
                        .name("fk-blog_articles-author_id-to-users")
                        .from(BlogArticles::Table, BlogArticles::AuthorId)
                        .to(Users::Table, Users::Id)
                        .on_delete(ForeignKeyAction::Cascade)
                        .on_update(ForeignKeyAction::Cascade),
                )
                .to_owned(),
        )
        .await?;

        create_index(m, "idx-blog_articles-slug", BlogArticles::Slug).await?;
        m.create_index(
            Index::create()
                .name("idx-blog_articles-published-published_at")
                .table(BlogArticles::Table)
                .col(BlogArticles::Published)
                .col(BlogArticles::PublishedAt)
                .to_owned(),
        )
        .await?;
        create_index(m, "idx-blog_articles-author_id", BlogArticles::AuthorId).await?;
        Ok(())
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.drop_table(Table::drop().table(BlogArticles::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(BlogArticles::Table)
            .col(col)
            .to_owned(),
    )
    .await
}
