use sea_orm_migration::prelude::*;

/// 为三个消息表添加缺失的 version 列（乐观锁字段）。
///
/// CLAUDE.md 要求所有表包含 version 字段用于乐观锁，但消息模块的三个表遗漏了。
#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        // message_templates
        manager
            .alter_table(
                Table::alter()
                    .table(MessageTemplates::Table)
                    .add_column(
                        ColumnDef::new(MessageTemplates::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await?;

        // messages
        manager
            .alter_table(
                Table::alter()
                    .table(Messages::Table)
                    .add_column(
                        ColumnDef::new(Messages::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await?;

        // message_subscriptions
        manager
            .alter_table(
                Table::alter()
                    .table(MessageSubscriptions::Table)
                    .add_column(
                        ColumnDef::new(MessageSubscriptions::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .alter_table(
                Table::alter()
                    .table(MessageTemplates::Table)
                    .drop_column(MessageTemplates::Version)
                    .to_owned(),
            )
            .await?;

        manager
            .alter_table(
                Table::alter()
                    .table(Messages::Table)
                    .drop_column(Messages::Version)
                    .to_owned(),
            )
            .await?;

        manager
            .alter_table(
                Table::alter()
                    .table(MessageSubscriptions::Table)
                    .drop_column(MessageSubscriptions::Version)
                    .to_owned(),
            )
            .await
    }
}

#[derive(DeriveIden)]
enum MessageTemplates {
    Table,
    Version,
}

#[derive(DeriveIden)]
enum Messages {
    Table,
    Version,
}

#[derive(DeriveIden)]
enum MessageSubscriptions {
    Table,
    Version,
}
