use crate::AppService;
use crate::error::AppError;
use models::users::user_activity_log;
use sea_orm::*;
use serde_json::json;
use session::Session;

impl AppService {
    pub async fn auth_logout(&self, context: &Session) -> Result<(), AppError> {
        if let Some(user_uid) = context.user() {
            tracing::info!(user_uid = %user_uid, ip = ?context.ip_address(), "User logged out");
            let _ = user_activity_log::ActiveModel {
                user_uid: Set(Option::from(user_uid)),
                action: Set("logout".to_string()),
                ip_address: Set(context.ip_address()),
                user_agent: Set(context.user_agent()),
                details: Set(json!({})),
                created_at: Set(chrono::Utc::now()),
                ..Default::default()
            }
            .insert(&self.db)
            .await;
        }
        context.clear_user();
        context.clear();
        Ok(())
    }
}
