use std::time::Duration;

use moka::sync::Cache;
use sea_orm::DatabaseConnection;

use erp_core::error::{AppError, AppResult};
use erp_core::events::EventBus;

use crate::engine::PluginEngine;

/// 插件模块共享状态 — 用于 Axum State 提取
#[derive(Clone)]
pub struct PluginState {
    pub db: DatabaseConnection,
    pub event_bus: EventBus,
    pub engine: PluginEngine,
    /// Schema 缓存 — key: "{plugin_id}:{entity_name}:{tenant_id}"
    pub entity_cache: Cache<String, EntityInfo>,
}

/// 缓存的实体信息
#[derive(Clone, Debug)]
pub struct EntityInfo {
    pub table_name: String,
    pub schema_json: serde_json::Value,
    pub generated_fields: Vec<String>,
}

impl EntityInfo {
    /// 从 schema_json 解析字段列表
    pub fn fields(&self) -> AppResult<Vec<crate::manifest::PluginField>> {
        let entity_def: crate::manifest::PluginEntity =
            serde_json::from_value(self.schema_json.clone())
                .map_err(|e| AppError::Internal(format!("解析 entity schema 失败: {}", e)))?;
        Ok(entity_def.fields)
    }
}

impl PluginState {
    pub fn new(db: DatabaseConnection, event_bus: EventBus, engine: PluginEngine) -> Self {
        let entity_cache = Cache::builder()
            .max_capacity(1000)
            .time_to_idle(Duration::from_secs(300))
            .build();
        Self {
            db,
            event_bus,
            engine,
            entity_cache,
        }
    }
}
