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(DictionaryItems::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(DictionaryItems::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(DictionaryItems::TenantId).uuid().not_null())
                    .col(
                        ColumnDef::new(DictionaryItems::DictionaryId)
                            .uuid()
                            .not_null(),
                    )
                    .col(ColumnDef::new(DictionaryItems::Label).string().not_null())
                    .col(ColumnDef::new(DictionaryItems::Value).string().not_null())
                    .col(
                        ColumnDef::new(DictionaryItems::SortOrder)
                            .integer()
                            .not_null()
                            .default(0),
                    )
                    .col(ColumnDef::new(DictionaryItems::Color).string().null())
                    .col(
                        ColumnDef::new(DictionaryItems::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(DictionaryItems::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(DictionaryItems::CreatedBy).uuid().not_null())
                    .col(ColumnDef::new(DictionaryItems::UpdatedBy).uuid().not_null())
                    .col(
                        ColumnDef::new(DictionaryItems::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(DictionaryItems::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_dict_items_dictionary")
                            .from(DictionaryItems::Table, DictionaryItems::DictionaryId)
                            .to(Dictionaries::Table, Dictionaries::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_dict_items_dictionary_id")
                    .table(DictionaryItems::Table)
                    .col(DictionaryItems::DictionaryId)
                    .to_owned(),
            )
            .await?;

        manager.get_connection().execute(sea_orm::Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "CREATE UNIQUE INDEX idx_dict_items_dict_value ON dictionary_items (dictionary_id, value) 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(DictionaryItems::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum Dictionaries {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum DictionaryItems {
    Table,
    Id,
    TenantId,
    DictionaryId,
    Label,
    Value,
    SortOrder,
    Color,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}
