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(NumberingRules::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(NumberingRules::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(NumberingRules::TenantId).uuid().not_null())
                    .col(ColumnDef::new(NumberingRules::Name).string().not_null())
                    .col(ColumnDef::new(NumberingRules::Code).string().not_null())
                    .col(
                        ColumnDef::new(NumberingRules::Prefix)
                            .string()
                            .not_null()
                            .default(""),
                    )
                    .col(ColumnDef::new(NumberingRules::DateFormat).string().null())
                    .col(
                        ColumnDef::new(NumberingRules::SeqLength)
                            .integer()
                            .not_null()
                            .default(4),
                    )
                    .col(
                        ColumnDef::new(NumberingRules::SeqStart)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .col(
                        ColumnDef::new(NumberingRules::SeqCurrent)
                            .big_integer()
                            .not_null()
                            .default(0),
                    )
                    .col(
                        ColumnDef::new(NumberingRules::Separator)
                            .string()
                            .not_null()
                            .default("-"),
                    )
                    .col(
                        ColumnDef::new(NumberingRules::ResetCycle)
                            .string()
                            .not_null()
                            .default("never"),
                    )
                    .col(ColumnDef::new(NumberingRules::LastResetDate).date().null())
                    .col(
                        ColumnDef::new(NumberingRules::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(NumberingRules::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(NumberingRules::CreatedBy).uuid().not_null())
                    .col(ColumnDef::new(NumberingRules::UpdatedBy).uuid().not_null())
                    .col(
                        ColumnDef::new(NumberingRules::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(NumberingRules::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await?;

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

        manager.get_connection().execute(sea_orm::Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "CREATE UNIQUE INDEX idx_numbering_rules_tenant_code ON numbering_rules (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(NumberingRules::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum NumberingRules {
    Table,
    Id,
    TenantId,
    Name,
    Code,
    Prefix,
    DateFormat,
    SeqLength,
    SeqStart,
    SeqCurrent,
    Separator,
    ResetCycle,
    LastResetDate,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}
