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,
            "admin_audit_logs",
            &[
                ("id", ColType::PkAuto),
                ("actor_username", ColType::StringNull),
                ("actor_email", ColType::StringNull),
                ("actor_source", ColType::StringNull),
                ("action", ColType::String),
                ("target_type", ColType::String),
                ("target_id", ColType::StringNull),
                ("target_label", ColType::StringNull),
                ("metadata", ColType::JsonBinaryNull),
            ],
            &[],
        )
        .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_admin_audit_logs_action_created_at")
                    .table(Alias::new("admin_audit_logs"))
                    .col(Alias::new("action"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_admin_audit_logs_target_type_created_at")
                    .table(Alias::new("admin_audit_logs"))
                    .col(Alias::new("target_type"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

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