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

/// Stored as `"ed25519"`, `"rsa"`, or `"ecdsa"` in the database.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyType {
    Ed25519,
    Rsa,
    Ecdsa,
}

impl std::fmt::Display for KeyType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyType::Ed25519 => write!(f, "ed25519"),
            KeyType::Rsa => write!(f, "rsa"),
            KeyType::Ecdsa => write!(f, "ecdsa"),
        }
    }
}

impl std::str::FromStr for KeyType {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ed25519" => Ok(KeyType::Ed25519),
            "rsa" => Ok(KeyType::Rsa),
            "ecdsa" => Ok(KeyType::Ecdsa),
            _ => Err("unknown key type"),
        }
    }
}

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "user_ssh_key")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub user: UserId,
    pub title: String,
    pub public_key: String,
    pub fingerprint: String,
    pub key_type: String,
    pub key_bits: Option<i32>,
    pub is_verified: bool,
    pub last_used_at: Option<DateTimeUtc>,
    pub expires_at: Option<DateTimeUtc>,
    pub is_revoked: bool,
    pub created_at: DateTimeUtc,
    pub updated_at: DateTimeUtc,
}

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

impl ActiveModelBehavior for ActiveModel {}
