use sea_orm_migration::prelude::*;

/// 为 tokens 表添加缺失的标准字段: updated_at, created_by, updated_by, deleted_at, version。
///
/// tokens 表原始迁移缺少 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(Tokens::Table)
                    .add_column(
                        ColumnDef::new(Tokens::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .add_column(
                        ColumnDef::new(Tokens::CreatedBy)
                            .uuid()
                            .not_null()
                            .default(Expr::val("00000000-0000-0000-0000-000000000000")),
                    )
                    .add_column(
                        ColumnDef::new(Tokens::UpdatedBy)
                            .uuid()
                            .not_null()
                            .default(Expr::val("00000000-0000-0000-0000-000000000000")),
                    )
                    .add_column(
                        ColumnDef::new(Tokens::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .add_column(
                        ColumnDef::new(Tokens::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await
    }

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

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