//! Session management utilities

use rustelo_core::{Result, RusteloError};
use std::collections::HashMap;

/// Session data
#[derive(Debug, Clone)]
pub struct Session {
    /// Session ID
    pub id: String,
    /// User ID
    pub user_id: Option<String>,
    /// Session data
    pub data: HashMap<String, String>,
}

/// Session manager
pub struct SessionManager {
    sessions: HashMap<String, Session>,
}

impl SessionManager {
    /// Create a new session manager
    pub fn new() -> Self {
        Self {
            sessions: HashMap::new(),
        }
    }

    /// Create a new session
    pub fn create_session(&mut self) -> String {
        let id = uuid::Uuid::new_v4().to_string();
        let session = Session {
            id: id.clone(),
            user_id: None,
            data: HashMap::new(),
        };
        self.sessions.insert(id.clone(), session);
        id
    }

    /// Get session by ID
    pub fn get_session(&self, id: &str) -> Option<&Session> {
        self.sessions.get(id)
    }

    /// Update session
    pub fn update_session(&mut self, id: &str, session: Session) -> Result<()> {
        if self.sessions.contains_key(id) {
            self.sessions.insert(id.to_string(), session);
            Ok(())
        } else {
            Err(RusteloError::generic("Session not found"))
        }
    }

    /// Delete session
    pub fn delete_session(&mut self, id: &str) -> Result<()> {
        if self.sessions.remove(id).is_some() {
            Ok(())
        } else {
            Err(RusteloError::generic("Session not found"))
        }
    }
}

impl Default for SessionManager {
    fn default() -> Self {
        Self::new()
    }
}
