//! Create refresh_token_families table.

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(RefreshTokenFamilies::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(RefreshTokenFamilies::Family)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(RefreshTokenFamilies::UserId).uuid().not_null())
                    .col(ColumnDef::new(RefreshTokenFamilies::Generation).integer().not_null().default(0))
                    .col(ColumnDef::new(RefreshTokenFamilies::Revoked).boolean().not_null().default(false))
                    .col(
                        ColumnDef::new(RefreshTokenFamilies::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .from(RefreshTokenFamilies::Table, RefreshTokenFamilies::UserId)
                            .to(super::m001_create_users::Users::Table, super::m001_create_users::Users::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await
    }

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

#[derive(DeriveIden)]
enum RefreshTokenFamilies {
    Table,
    Family,
    UserId,
    Generation,
    Revoked,
    CreatedAt,
}
