use loco_rs::schema::*;
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> {
        create_table(
            manager,
            "notification_deliveries",
            &[
                ("id", ColType::PkAuto),
                ("subscription_id", ColType::IntegerNull),
                ("channel_type", ColType::String),
                ("target", ColType::String),
                ("event_type", ColType::String),
                ("status", ColType::String),
                ("provider", ColType::StringNull),
                ("response_text", ColType::TextNull),
                ("payload", ColType::JsonBinaryNull),
                ("delivered_at", ColType::StringNull),
            ],
            &[],
        )
        .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_notification_deliveries_event_created_at")
                    .table(Alias::new("notification_deliveries"))
                    .col(Alias::new("event_type"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_notification_deliveries_subscription_created_at")
                    .table(Alias::new("notification_deliveries"))
                    .col(Alias::new("subscription_id"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        for index_name in [
            "idx_notification_deliveries_subscription_created_at",
            "idx_notification_deliveries_event_created_at",
        ] {
            manager
                .drop_index(
                    Index::drop()
                        .name(index_name)
                        .table(Alias::new("notification_deliveries"))
                        .to_owned(),
                )
                .await?;
        }

        drop_table(manager, "notification_deliveries").await
    }
}
