use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::domain::ids::{TokenId, UserId};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Token {
    pub id: TokenId,
    pub user_id: UserId,
    #[serde(skip_serializing)]
    pub token_hash: String,
    pub name: String,
    pub created_at: DateTime<Utc>,
    pub last_used_at: Option<DateTime<Utc>>,
    pub revoked_at: Option<DateTime<Utc>>,
}

#[derive(Clone)]
pub struct NewToken {
    pub user_id: UserId,
    pub token_hash: String,
    pub name: String,
}

impl std::fmt::Debug for NewToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NewToken")
            .field("user_id", &self.user_id)
            .field("token_hash", &"<redacted>")
            .field("name", &self.name)
            .finish()
    }
}

impl Token {
    pub fn new(
        id: TokenId,
        user_id: UserId,
        token_hash: String,
        name: String,
        created_at: DateTime<Utc>,
        last_used_at: Option<DateTime<Utc>>,
        revoked_at: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            id,
            user_id,
            token_hash,
            name,
            created_at,
            last_used_at,
            revoked_at,
        }
    }

    pub fn is_revoked(&self) -> bool {
        self.revoked_at.is_some()
    }

    pub fn is_active(&self) -> bool {
        !self.is_revoked()
    }
}

impl NewToken {
    pub fn new(user_id: UserId, token_hash: String, name: String) -> Self {
        Self {
            user_id,
            token_hash,
            name,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn token_active_when_not_revoked() {
        let now = Utc::now();
        let token = Token::new(
            TokenId::new(1),
            UserId::new(1),
            "hash".to_string(),
            "my-token".to_string(),
            now,
            None,
            None,
        );
        assert!(token.is_active());
        assert!(!token.is_revoked());
    }

    #[test]
    fn token_revoked() {
        let now = Utc::now();
        let token = Token::new(
            TokenId::new(1),
            UserId::new(1),
            "hash".to_string(),
            "my-token".to_string(),
            now,
            None,
            Some(now),
        );
        assert!(token.is_revoked());
        assert!(!token.is_active());
    }
}
