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(Dictionaries::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Dictionaries::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Dictionaries::TenantId).uuid().not_null())
                    .col(ColumnDef::new(Dictionaries::Name).string().not_null())
                    .col(ColumnDef::new(Dictionaries::Code).string().not_null())
                    .col(ColumnDef::new(Dictionaries::Description).text().null())
                    .col(
                        ColumnDef::new(Dictionaries::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(Dictionaries::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(Dictionaries::CreatedBy).uuid().not_null())
                    .col(ColumnDef::new(Dictionaries::UpdatedBy).uuid().not_null())
                    .col(
                        ColumnDef::new(Dictionaries::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(Dictionaries::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_dictionaries_tenant_id")
                    .table(Dictionaries::Table)
                    .col(Dictionaries::TenantId)
                    .to_owned(),
            )
            .await?;

        manager.get_connection().execute(sea_orm::Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "CREATE UNIQUE INDEX idx_dictionaries_tenant_code ON dictionaries (tenant_id, code) WHERE deleted_at IS NULL".to_string(),
        )).await.map_err(|e| DbErr::Custom(e.to_string()))?;

        Ok(())
    }

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

#[derive(DeriveIden)]
enum Dictionaries {
    Table,
    Id,
    TenantId,
    Name,
    Code,
    Description,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}
