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

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(DeriveIden)]
enum SitePages {
    Table,
    Id,
    Slug,
    Title,
    Content,
    CreatedAt,
    UpdatedAt,
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.create_table(
            Table::create()
                .table(SitePages::Table)
                .if_not_exists()
                .col(
                    ColumnDef::new(SitePages::Id)
                        .uuid()
                        .not_null()
                        .primary_key(),
                )
                .col(
                    ColumnDef::new(SitePages::Slug)
                        .string_len(100)
                        .not_null()
                        .unique_key(),
                )
                .col(ColumnDef::new(SitePages::Title).string_len(500).not_null())
                .col(ColumnDef::new(SitePages::Content).text().not_null())
                .col(
                    ColumnDef::new(SitePages::CreatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .col(
                    ColumnDef::new(SitePages::UpdatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .to_owned(),
        )
        .await?;

        m.get_connection()
            .execute_unprepared(
                "INSERT INTO site_pages (id, slug, title, content, created_at, updated_at) \
                 VALUES (gen_random_uuid(), 'about', 'About', '', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) \
                 ON CONFLICT (slug) DO NOTHING",
            )
            .await?;

        Ok(())
    }

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