use sea_orm::DatabaseBackend;
use sea_orm::Statement;
use sea_orm_migration::prelude::*;

/// Recreate unique indexes on roles and permissions to include soft-delete awareness.
#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "DROP INDEX IF EXISTS idx_roles_tenant_code".to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "DROP INDEX IF EXISTS idx_permissions_tenant_code".to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "CREATE UNIQUE INDEX idx_roles_tenant_code \
                 ON roles (tenant_id, code) \
                 WHERE deleted_at IS NULL"
                    .to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "CREATE UNIQUE INDEX idx_permissions_tenant_code \
                 ON permissions (tenant_id, code) \
                 WHERE deleted_at IS NULL"
                    .to_string(),
            ))
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "DROP INDEX IF EXISTS idx_roles_tenant_code".to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "DROP INDEX IF EXISTS idx_permissions_tenant_code".to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "CREATE UNIQUE INDEX idx_roles_tenant_code \
                 ON roles (tenant_id, code)"
                    .to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DatabaseBackend::Postgres,
                "CREATE UNIQUE INDEX idx_permissions_tenant_code \
                 ON permissions (tenant_id, code)"
                    .to_string(),
            ))
            .await?;

        Ok(())
    }
}
