use loco_rs::schema::*;
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        create_table(
            manager,
            "post_revisions",
            &[
                ("id", ColType::PkAuto),
                ("post_slug", ColType::String),
                ("post_title", ColType::StringNull),
                ("operation", ColType::String),
                ("revision_reason", ColType::TextNull),
                ("actor_username", ColType::StringNull),
                ("actor_email", ColType::StringNull),
                ("actor_source", ColType::StringNull),
                ("markdown", ColType::TextNull),
                ("metadata", ColType::JsonBinaryNull),
            ],
            &[],
        )
        .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_post_revisions_post_slug_created_at")
                    .table(Alias::new("post_revisions"))
                    .col(Alias::new("post_slug"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_post_revisions_operation_created_at")
                    .table(Alias::new("post_revisions"))
                    .col(Alias::new("operation"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        for index_name in [
            "idx_post_revisions_operation_created_at",
            "idx_post_revisions_post_slug_created_at",
        ] {
            manager
                .drop_index(
                    Index::drop()
                        .name(index_name)
                        .table(Alias::new("post_revisions"))
                        .to_owned(),
                )
                .await?;
        }

        drop_table(manager, "post_revisions").await
    }
}
