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(ReminderTaskRecipient::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ReminderTaskRecipient::TaskId)
                            .uuid()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ReminderTaskRecipient::UserId)
                            .uuid()
                            .not_null(),
                    )
                    .primary_key(
                        Index::create()
                            .col(ReminderTaskRecipient::TaskId)
                            .col(ReminderTaskRecipient::UserId),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("FK_reminder_task_recipient_task")
                            .from(ReminderTaskRecipient::Table, ReminderTaskRecipient::TaskId)
                            .to(ReminderTask::Table, ReminderTask::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("FK_reminder_task_recipient_user")
                            .from(ReminderTaskRecipient::Table, ReminderTaskRecipient::UserId)
                            .to(User::Table, User::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;

        // Create index on user_id for reverse lookups
        manager
            .create_index(
                Index::create()
                    .name("IDX_reminder_task_recipient_user_id")
                    .table(ReminderTaskRecipient::Table)
                    .col(ReminderTaskRecipient::UserId)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

#[derive(DeriveIden)]
enum ReminderTaskRecipient {
    Table,
    TaskId,
    UserId,
}

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

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