use sea_orm_migration::prelude::*;

use crate::m20220101_000002_create_enums::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(ReminderOffset::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ReminderOffset::Id)
                            .uuid()
                            .primary_key()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ReminderOffset::TargetType)
                            .custom(TargetType::Type)
                            .not_null(),
                    )
                    .col(ColumnDef::new(ReminderOffset::TargetId).uuid().not_null())
                    .col(
                        ColumnDef::new(ReminderOffset::OffsetMinutes)
                            .integer()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ReminderOffset::ChannelInapp)
                            .boolean()
                            .not_null()
                            .default(true),
                    )
                    .col(
                        ColumnDef::new(ReminderOffset::ChannelBark)
                            .boolean()
                            .not_null()
                            .default(false),
                    )
                    .col(
                        ColumnDef::new(ReminderOffset::CreatedAt)
                            .timestamp()
                            .not_null()
                            .extra("DEFAULT NOW()"),
                    )
                    .to_owned(),
            )
            .await?;

        // Create index for polymorphic lookup
        manager
            .create_index(
                Index::create()
                    .name("IDX_reminder_offset_target")
                    .table(ReminderOffset::Table)
                    .col(ReminderOffset::TargetType)
                    .col(ReminderOffset::TargetId)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

#[derive(DeriveIden)]
enum ReminderOffset {
    Table,
    Id,
    TargetType,
    TargetId,
    OffsetMinutes,
    ChannelInapp,
    ChannelBark,
    CreatedAt,
}
