use loco_rs::schema::*;
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

// Optional TOTP (Google Authenticator) two-factor auth. All three columns are
// nullable and only populated once a user opts in:
//   - `totp_secret`         base32 shared secret; present while enrolling/enabled.
//                           TODO(security): stored PLAINTEXT and is password-
//                           equivalent (must stay reversible to recompute codes).
//                           Encrypt at rest later with an out-of-DB key. See the
//                           TODO(security) block in src/models/users.rs.
//   - `totp_enabled_at`     NULL = 2FA off. Set only after the user confirms a
//                           code, so a half-finished enrollment never gates login.
//   - `totp_backup_codes`   JSON array of hashed one-time recovery codes.
#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        add_column(m, "users", "totp_secret", ColType::TextNull).await?;
        add_column(m, "users", "totp_enabled_at", ColType::TimestampWithTimeZoneNull).await?;
        add_column(m, "users", "totp_backup_codes", ColType::TextNull).await?;
        Ok(())
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        remove_column(m, "users", "totp_backup_codes").await?;
        remove_column(m, "users", "totp_enabled_at").await?;
        remove_column(m, "users", "totp_secret").await?;
        Ok(())
    }
}
