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(UserSession::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(UserSession::Id).string().not_null().primary_key())
                    .col(ColumnDef::new(UserSession::User).string().not_null())
                    .col(ColumnDef::new(UserSession::DisplayId).string().not_null())
                    .col(ColumnDef::new(UserSession::Token).string().not_null().unique_key())
                    .col(ColumnDef::new(UserSession::Flags).big_unsigned().not_null())
                    .col(ColumnDef::new(UserSession::IPAddress).string())
                    .col(ColumnDef::new(UserSession::CreatedOn).date_time().not_null())
                    .col(ColumnDef::new(UserSession::DeathDate).date_time().not_null())
                    .foreign_key(ForeignKey::create()
                        .name("fk-usersession-user")
                        .from(UserSession::Table, UserSession::User)
                        .to(User::Table, User::Id)
                        .on_delete(ForeignKeyAction::Cascade))
                    .to_owned(),
            )
            .await
    }

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

#[derive(DeriveIden)]
enum UserSession {
    Table,
    Id,
    User,
    DisplayId,
    Token,
    Flags,
    IPAddress,
    CreatedOn,
    DeathDate,
}
