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> {
        let conn = manager.get_connection();

        conn.execute_unprepared("ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS prev_hash TEXT")
            .await?;

        conn.execute_unprepared("ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS record_hash TEXT")
            .await?;

        // 为 record_hash 创建索引（用于快速查找最新哈希）
        conn.execute_unprepared(
            "CREATE INDEX IF NOT EXISTS idx_audit_logs_record_hash
             ON audit_logs (record_hash) WHERE record_hash IS NOT NULL",
        )
        .await?;

        // 按 tenant_id + created_at DESC 查找最新哈希的索引
        conn.execute_unprepared(
            "CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_created
             ON audit_logs (tenant_id, created_at DESC)",
        )
        .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let conn = manager.get_connection();

        conn.execute_unprepared("DROP INDEX IF EXISTS idx_audit_logs_tenant_created")
            .await?;

        conn.execute_unprepared("DROP INDEX IF EXISTS idx_audit_logs_record_hash")
            .await?;

        conn.execute_unprepared("ALTER TABLE audit_logs DROP COLUMN IF EXISTS record_hash")
            .await?;

        conn.execute_unprepared("ALTER TABLE audit_logs DROP COLUMN IF EXISTS prev_hash")
            .await?;

        Ok(())
    }
}
