//! Create webhook_processed_events table for idempotency tracking.

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(WebhookProcessedEvents::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(WebhookProcessedEvents::EventId)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(
                        ColumnDef::new(WebhookProcessedEvents::ProcessedAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_webhook_processed_events_processed_at")
                    .table(WebhookProcessedEvents::Table)
                    .col(WebhookProcessedEvents::ProcessedAt)
                    .to_owned(),
            )
            .await
    }

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

#[derive(DeriveIden)]
enum WebhookProcessedEvents {
    Table,
    EventId,
    ProcessedAt,
}
