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,
            "subscriptions",
            &[
                ("id", ColType::PkAuto),
                ("channel_type", ColType::String),
                ("target", ColType::String),
                ("display_name", ColType::StringNull),
                ("status", ColType::String),
                ("filters", ColType::JsonBinaryNull),
                ("secret", ColType::TextNull),
                ("notes", ColType::TextNull),
                ("verified_at", ColType::StringNull),
                ("last_notified_at", ColType::StringNull),
                ("failure_count", ColType::IntegerNull),
                ("last_delivery_status", ColType::StringNull),
            ],
            &[],
        )
        .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_subscriptions_channel_status")
                    .table(Alias::new("subscriptions"))
                    .col(Alias::new("channel_type"))
                    .col(Alias::new("status"))
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_subscriptions_channel_target_unique")
                    .table(Alias::new("subscriptions"))
                    .col(Alias::new("channel_type"))
                    .col(Alias::new("target"))
                    .unique()
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

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