use sea_orm_migration::prelude::*;

/// 为 process_variables 表添加缺失的标准字段: created_at, updated_at, created_by, updated_by, deleted_at, version。
///
/// process_variables 表原始迁移缺少 ERP 标准要求的审计和乐观锁字段。
#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .alter_table(
                Table::alter()
                    .table(ProcessVariables::Table)
                    .add_column(
                        ColumnDef::new(ProcessVariables::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .add_column(
                        ColumnDef::new(ProcessVariables::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .add_column(
                        ColumnDef::new(ProcessVariables::CreatedBy)
                            .uuid()
                            .not_null()
                            .default(Expr::val("00000000-0000-0000-0000-000000000000")),
                    )
                    .add_column(
                        ColumnDef::new(ProcessVariables::UpdatedBy)
                            .uuid()
                            .not_null()
                            .default(Expr::val("00000000-0000-0000-0000-000000000000")),
                    )
                    .add_column(
                        ColumnDef::new(ProcessVariables::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .add_column(
                        ColumnDef::new(ProcessVariables::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .alter_table(
                Table::alter()
                    .table(ProcessVariables::Table)
                    .drop_column(ProcessVariables::CreatedAt)
                    .drop_column(ProcessVariables::UpdatedAt)
                    .drop_column(ProcessVariables::CreatedBy)
                    .drop_column(ProcessVariables::UpdatedBy)
                    .drop_column(ProcessVariables::DeletedAt)
                    .drop_column(ProcessVariables::Version)
                    .to_owned(),
            )
            .await
    }
}

#[derive(DeriveIden)]
enum ProcessVariables {
    Table,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}
