//! Plugin de configuração da aplicação (loja, preferências)
//! Persistido em config.json ao lado do banco SQLite.

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::sync::Mutex;
use tauri::State;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppConfig {
    pub loja: String,
    pub pdv_nome: String,
    pub operador_default: String,
    pub turno_default: String,
    pub sync_automatico: bool,
    pub auto_open_printer: bool,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            loja: "Uniao".to_string(),
            pdv_nome: "PDV-01".to_string(),
            operador_default: String::new(),
            turno_default: String::new(),
            sync_automatico: true,
            auto_open_printer: false,
        }
    }
}

pub struct AppState {
    pub config: Mutex<AppConfig>,
    config_path: PathBuf,
}

impl AppState {
    pub fn new(data_dir: PathBuf) -> Self {
        let config_path = data_dir.join("config.json");
        let config = if let Ok(content) = fs::read_to_string(&config_path) {
            serde_json::from_str(&content).unwrap_or_default()
        } else {
            AppConfig::default()
        };

        Self {
            config: Mutex::new(config),
            config_path,
        }
    }

    pub fn save(&self) -> Result<(), String> {
        let cfg = self.config.lock().map_err(|_| "lock error")?;
        let json = serde_json::to_string_pretty(&*cfg)
            .map_err(|e| e.to_string())?;
        fs::write(&self.config_path, json).map_err(|e| e.to_string())?;
        log::info!("Config salvo em {:?}", self.config_path);
        Ok(())
    }
}

#[tauri::command]
pub fn get_loja(state: State<'_, AppState>) -> String {
    state.config.lock().unwrap().loja.clone()
}

#[tauri::command]
pub fn set_loja(state: State<'_, AppState>, loja: String) -> Result<(), String> {
    state.config.lock().unwrap().loja = loja;
    state.save()
}

#[tauri::command]
pub fn get_config(state: State<'_, AppState>) -> AppConfig {
    state.config.lock().unwrap().clone()
}

#[tauri::command]
pub fn set_config(state: State<'_, AppState>, cfg: AppConfig) -> Result<(), String> {
    *state.config.lock().unwrap() = cfg;
    state.save()
}

pub fn init(data_dir: PathBuf) -> AppState {
    AppState::new(data_dir)
}
