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

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(DeriveIden)]
enum AuditLogs {
    Table,
    Id,
    AdminUserId,
    Action,
    TargetType,
    TargetId,
    Details,
    IpAddress,
    UserAgent,
    CreatedAt,
}

#[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(AuditLogs::Table)
                .if_not_exists()
                .col(
                    ColumnDef::new(AuditLogs::Id)
                        .uuid()
                        .not_null()
                        .primary_key(),
                )
                .col(ColumnDef::new(AuditLogs::AdminUserId).integer().not_null())
                .col(ColumnDef::new(AuditLogs::Action).string_len(100).not_null())
                .col(ColumnDef::new(AuditLogs::TargetType).string_len(50).null())
                .col(ColumnDef::new(AuditLogs::TargetId).uuid().null())
                .col(ColumnDef::new(AuditLogs::Details).json_binary().null())
                .col(ColumnDef::new(AuditLogs::IpAddress).inet().null())
                .col(ColumnDef::new(AuditLogs::UserAgent).text().null())
                .col(
                    ColumnDef::new(AuditLogs::CreatedAt)
                        .timestamp_with_time_zone()
                        .not_null()
                        .default(Expr::current_timestamp()),
                )
                .foreign_key(
                    ForeignKey::create()
                        .name("fk-audit_logs-admin_user_id-to-users")
                        .from(AuditLogs::Table, AuditLogs::AdminUserId)
                        .to(Users::Table, Users::Id)
                        .on_delete(ForeignKeyAction::Cascade)
                        .on_update(ForeignKeyAction::Cascade),
                )
                .to_owned(),
        )
        .await?;

        create_index(m, "idx-audit_logs-admin_user_id", AuditLogs::AdminUserId).await?;
        create_index(m, "idx-audit_logs-action", AuditLogs::Action).await?;
        m.create_index(
            Index::create()
                .name("idx-audit_logs-target")
                .table(AuditLogs::Table)
                .col(AuditLogs::TargetType)
                .col(AuditLogs::TargetId)
                .to_owned(),
        )
        .await?;
        create_index(m, "idx-audit_logs-created_at", AuditLogs::CreatedAt).await?;
        Ok(())
    }

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