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(UserTokens::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(UserTokens::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(UserTokens::TenantId).uuid().not_null())
                    .col(ColumnDef::new(UserTokens::UserId).uuid().not_null())
                    .col(
                        ColumnDef::new(UserTokens::TokenHash)
                            .string()
                            .not_null()
                            .unique_key(),
                    )
                    .col(ColumnDef::new(UserTokens::TokenType).string().not_null())
                    .col(
                        ColumnDef::new(UserTokens::ExpiresAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(UserTokens::RevokedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(ColumnDef::new(UserTokens::DeviceInfo).string().null())
                    .col(
                        ColumnDef::new(UserTokens::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(UserTokens::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(UserTokens::CreatedBy).uuid().not_null())
                    .col(ColumnDef::new(UserTokens::UpdatedBy).uuid().not_null())
                    .col(
                        ColumnDef::new(UserTokens::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(UserTokens::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .foreign_key(
                        &mut ForeignKey::create()
                            .name("fk_user_tokens_user_id")
                            .from(UserTokens::Table, UserTokens::UserId)
                            .to(Users::Table, Users::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .to_owned(),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_user_tokens_tenant_id")
                    .table(UserTokens::Table)
                    .col(UserTokens::TenantId)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_user_tokens_user_id")
                    .table(UserTokens::Table)
                    .col(UserTokens::UserId)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_user_tokens_token_hash")
                    .table(UserTokens::Table)
                    .col(UserTokens::TokenHash)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

#[derive(DeriveIden)]
enum UserTokens {
    Table,
    Id,
    TenantId,
    UserId,
    TokenHash,
    TokenType,
    ExpiresAt,
    RevokedAt,
    DeviceInfo,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}

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