//! Garage repository implementation for vehicle data persistence operations.
//!
//! This module provides the data access layer for vehicle garage management.
//! Each player's garage is stored as a single JSON string containing all their vehicles.

use forge_models::{Garage, Vehicle};
use forge_shared::RedisClient;
use std::collections::HashMap;

/// Repository trait defining the contract for garage data operations.
pub trait GarageRepository: Send + Sync {
    /// Creates a new garage for a player
    fn create(&self, uid: &str, garage: &Garage) -> Result<(), String>;

    /// Updates an existing garage with new vehicle data
    fn update(&self, uid: &str, garage: &Garage) -> Result<(), String>;

    /// Retrieves a player's garage
    fn get(&self, uid: &str) -> Result<Option<Garage>, String>;

    /// Deletes a player's garage (all vehicles)
    fn delete(&self, uid: &str) -> Result<(), String>;

    /// Checks if a player has a garage
    fn exists(&self, uid: &str) -> Result<bool, String>;
}

/// Redis-based implementation of the GarageRepository trait.
///
/// Stores each player's garage as a single JSON string array with the key format `garage:{uid}`.
pub struct RedisGarageRepository<C: RedisClient> {
    client: C,
}

impl<C: RedisClient> RedisGarageRepository<C> {
    pub fn new(client: C) -> Self {
        Self { client }
    }
}

impl<C: RedisClient> GarageRepository for RedisGarageRepository<C> {
    fn create(&self, uid: &str, garage: &Garage) -> Result<(), String> {
        let redis_key = format!("garage:{}", uid);

        // Serialize just the vehicles array
        let garage_json = serde_json::to_string(&garage.vehicles)
            .map_err(|e| format!("Failed to serialize garage: {}", e))?;

        // Store as a simple string value
        self.client.set_key(redis_key, garage_json)
    }

    fn update(&self, uid: &str, garage: &Garage) -> Result<(), String> {
        let redis_key = format!("garage:{}", uid);

        // Serialize just the vehicles array
        let garage_json = serde_json::to_string(&garage.vehicles)
            .map_err(|e| format!("Failed to serialize garage: {}", e))?;

        // Update the existing garage
        self.client.set_key(redis_key, garage_json)
    }

    fn get(&self, uid: &str) -> Result<Option<Garage>, String> {
        let redis_key = format!("garage:{}", uid);

        // Get the JSON string from Redis
        let garage_string = self.client.get_key(redis_key)?;

        // Return None if no data found
        if garage_string.is_empty() {
            return Ok(None);
        }

        // Deserialize the vehicles data
        match serde_json::from_str::<HashMap<String, Vehicle>>(&garage_string) {
            Ok(vehicles) => Ok(Some(Garage { vehicles })),
            Err(e) => Err(format!("Failed to deserialize garage: {}", e)),
        }
    }

    fn delete(&self, uid: &str) -> Result<(), String> {
        let redis_key = format!("garage:{}", uid);
        self.client.delete_key(redis_key)
    }

    fn exists(&self, uid: &str) -> Result<bool, String> {
        let redis_key = format!("garage:{}", uid);
        self.client.key_exists(redis_key)
    }
}
