use sea_orm_migration::prelude::*;

use crate::m20220101_000002_create_enums::{ChannelType, NotificationStatus, TargetType};

#[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(Notification::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Notification::Id)
                            .uuid()
                            .primary_key()
                            .not_null(),
                    )
                    .col(ColumnDef::new(Notification::RecipientId).uuid().not_null())
                    .col(
                        ColumnDef::new(Notification::TargetType)
                            .custom(TargetType::Type)
                            .not_null(),
                    )
                    .col(ColumnDef::new(Notification::TargetId).uuid().not_null())
                    .col(
                        ColumnDef::new(Notification::TriggerAt)
                            .timestamp()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(Notification::Channel)
                            .custom(ChannelType::Type)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(Notification::Status)
                            .custom(NotificationStatus::Type)
                            .not_null()
                            .default("pending"),
                    )
                    .col(ColumnDef::new(Notification::LockedAt).timestamp().null())
                    .col(ColumnDef::new(Notification::SentAt).timestamp().null())
                    .col(ColumnDef::new(Notification::ReadAt).timestamp().null())
                    .col(
                        ColumnDef::new(Notification::CreatedAt)
                            .timestamp()
                            .not_null()
                            .extra("DEFAULT NOW()"),
                    )
                    .col(
                        ColumnDef::new(Notification::UpdatedAt)
                            .timestamp()
                            .not_null(),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("FK_notification_recipient")
                            .from(Notification::Table, Notification::RecipientId)
                            .to(User::Table, User::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;

        // Create unique constraint
        manager
            .create_index(
                Index::create()
                    .name("UQ_notification_recipient_target_trigger_channel")
                    .table(Notification::Table)
                    .col(Notification::RecipientId)
                    .col(Notification::TargetType)
                    .col(Notification::TargetId)
                    .col(Notification::TriggerAt)
                    .col(Notification::Channel)
                    .unique()
                    .to_owned(),
            )
            .await?;

        // Create indexes
        manager
            .create_index(
                Index::create()
                    .name("IDX_notification_status_trigger")
                    .table(Notification::Table)
                    .col(Notification::Status)
                    .col(Notification::TriggerAt)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("IDX_notification_recipient_read")
                    .table(Notification::Table)
                    .col(Notification::RecipientId)
                    .col(Notification::ReadAt)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

#[derive(DeriveIden)]
enum Notification {
    Table,
    Id,
    RecipientId,
    TargetType,
    TargetId,
    TriggerAt,
    Channel,
    Status,
    LockedAt,
    SentAt,
    ReadAt,
    CreatedAt,
    UpdatedAt,
}

#[derive(DeriveIden)]
enum User {
    Table,
    Id,
}
