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> {
        manager
            .create_table(
                Table::create()
                    .table(MenuRoles::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(MenuRoles::MenuId).uuid().not_null())
                    .col(ColumnDef::new(MenuRoles::RoleId).uuid().not_null())
                    .col(ColumnDef::new(MenuRoles::TenantId).uuid().not_null())
                    .col(ColumnDef::new(MenuRoles::Id).uuid().not_null())
                    .col(
                        ColumnDef::new(MenuRoles::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(MenuRoles::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(MenuRoles::CreatedBy).uuid().not_null())
                    .col(ColumnDef::new(MenuRoles::UpdatedBy).uuid().not_null())
                    .col(
                        ColumnDef::new(MenuRoles::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(MenuRoles::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .primary_key(Index::create().col(MenuRoles::Id))
                    .to_owned(),
            )
            .await?;

        manager.get_connection().execute(sea_orm::Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "CREATE UNIQUE INDEX idx_menu_roles_unique ON menu_roles (menu_id, role_id) WHERE deleted_at IS NULL".to_string(),
        )).await.map_err(|e| DbErr::Custom(e.to_string()))?;

        manager
            .create_index(
                Index::create()
                    .name("idx_menu_roles_menu_id")
                    .table(MenuRoles::Table)
                    .col(MenuRoles::MenuId)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_menu_roles_role_id")
                    .table(MenuRoles::Table)
                    .col(MenuRoles::RoleId)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(MenuRoles::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum MenuRoles {
    Table,
    Id,
    MenuId,
    RoleId,
    TenantId,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}
