use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(Iden)]
enum DeadLetterEvent {
    Table,
    Id,
    TenantId,
    OriginalEventId,
    EventType,
    Payload,
    ConsumerId,
    Attempts,
    LastError,
    CreatedAt,
    ResolvedAt,
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(DeadLetterEvent::Table)
                    .col(
                        ColumnDef::new(DeadLetterEvent::Id)
                            .uuid()
                            .not_null()
                            .primary_key()
                            .default(PgFunc::gen_random_uuid()),
                    )
                    .col(ColumnDef::new(DeadLetterEvent::TenantId).uuid())
                    .col(
                        ColumnDef::new(DeadLetterEvent::OriginalEventId)
                            .uuid()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(DeadLetterEvent::EventType)
                            .string_len(128)
                            .not_null(),
                    )
                    .col(ColumnDef::new(DeadLetterEvent::Payload).json_binary())
                    .col(
                        ColumnDef::new(DeadLetterEvent::ConsumerId)
                            .string_len(128)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(DeadLetterEvent::Attempts)
                            .integer()
                            .not_null()
                            .default(0),
                    )
                    .col(ColumnDef::new(DeadLetterEvent::LastError).text())
                    .col(
                        ColumnDef::new(DeadLetterEvent::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(DeadLetterEvent::ResolvedAt).timestamp_with_time_zone())
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(DeadLetterEvent::Table).to_owned())
            .await
    }
}
