use crate::{DateTimeUtc, UserId};
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

/// Stored as `"totp"` or `"webauthn"` in the database.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TwoFactorMethod {
    Totp,
    WebAuthn,
}

impl std::fmt::Display for TwoFactorMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TwoFactorMethod::Totp => write!(f, "totp"),
            TwoFactorMethod::WebAuthn => write!(f, "webauthn"),
        }
    }
}

impl std::str::FromStr for TwoFactorMethod {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "totp" => Ok(TwoFactorMethod::Totp),
            "webauthn" => Ok(TwoFactorMethod::WebAuthn),
            _ => Err("unknown two-factor method"),
        }
    }
}

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "user_2fa")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub user: UserId,
    pub method: String,
    pub secret: Option<String>,
    #[sea_orm(column_type = "Json")]
    pub backup_codes: serde_json::Value,
    pub is_enabled: bool,
    pub created_at: DateTimeUtc,
    pub updated_at: DateTimeUtc,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
