use sea_orm_migration::{prelude::*, schema::*};
use crate::m20240814_013106_create_user::User;

#[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(InviteCode::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(InviteCode::Id).string().not_null().primary_key())
                    .col(ColumnDef::new(InviteCode::Code).string().not_null().unique_key())
                    .col(ColumnDef::new(InviteCode::Issuer).string())
                    .col(ColumnDef::new(InviteCode::RootIssuer).string().not_null())
                    .col(ColumnDef::new(InviteCode::Comment).string())
                    .col(ColumnDef::new(InviteCode::CreatedOn).date_time().not_null())
                    .col(ColumnDef::new(InviteCode::Used).boolean().not_null())
                    .col(ColumnDef::new(InviteCode::UsedOn).date_time())
                    .col(ColumnDef::new(InviteCode::UsedBy).string())
                    .col(ColumnDef::new(InviteCode::Flags).big_unsigned())
                    .foreign_key(ForeignKey::create().name("fk-invitecode-usedby")
                        .from(InviteCode::Table, InviteCode::UsedBy)
                        .to(User::Table, User::Id)
                        .on_delete(ForeignKeyAction::SetNull))
                    .to_owned(),
            )
            .await
    }

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

#[derive(DeriveIden)]
pub enum InviteCode {
    Table,
    Id,
    Code,
    Issuer,
    RootIssuer,
    Comment,
    CreatedOn,
    Used,
    UsedOn,
    UsedBy,
    Flags,
}
