use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

/// 项目-模板绑定实体模型
/// 遵循 Tauri 开发规范的数据模型设计原则
/// 支持多对多关系管理，一个项目可以绑定多个模板，一个模板可以被多个项目使用
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectTemplateBinding {
    pub id: String,
    pub project_id: String,
    pub template_id: String,
    pub binding_name: Option<String>, // 绑定的自定义名称
    pub description: Option<String>,
    pub priority: u32, // 绑定优先级，数值越小优先级越高
    pub is_active: bool,
    pub binding_type: BindingType,
    pub binding_status: BindingStatus,
    pub metadata: Option<String>, // JSON格式的额外元数据
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// 绑定类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BindingType {
    /// 主要绑定 - 项目的主要模板
    Primary,
    /// 次要绑定 - 项目的备用模板
    Secondary,
    /// 参考绑定 - 仅作为参考的模板
    Reference,
    /// 测试绑定 - 用于测试的模板
    Test,
}

/// 绑定状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BindingStatus {
    /// 活跃状态 - 正在使用
    Active,
    /// 暂停状态 - 暂时不使用
    Paused,
    /// 已完成 - 已完成使用
    Completed,
    /// 已取消 - 取消绑定
    Cancelled,
}

impl ProjectTemplateBinding {
    /// 创建新的项目-模板绑定实例
    pub fn new(
        project_id: String,
        template_id: String,
        binding_type: BindingType,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            project_id,
            template_id,
            binding_name: None,
            description: None,
            priority: 0,
            is_active: true,
            binding_type,
            binding_status: BindingStatus::Active,
            metadata: None,
            created_at: now,
            updated_at: now,
        }
    }

    /// 更新绑定信息
    pub fn update(
        &mut self,
        binding_name: Option<String>,
        description: Option<String>,
        priority: Option<u32>,
        binding_type: Option<BindingType>,
        binding_status: Option<BindingStatus>,
    ) {
        if binding_name.is_some() {
            self.binding_name = binding_name;
        }
        if description.is_some() {
            self.description = description;
        }
        if let Some(priority) = priority {
            self.priority = priority;
        }
        if let Some(binding_type) = binding_type {
            self.binding_type = binding_type;
        }
        if let Some(binding_status) = binding_status {
            self.binding_status = binding_status;
        }
        self.updated_at = Utc::now();
    }

    /// 激活绑定
    pub fn activate(&mut self) {
        self.is_active = true;
        self.binding_status = BindingStatus::Active;
        self.updated_at = Utc::now();
    }

    /// 停用绑定
    pub fn deactivate(&mut self) {
        self.is_active = false;
        self.binding_status = BindingStatus::Paused;
        self.updated_at = Utc::now();
    }

    /// 完成绑定
    pub fn complete(&mut self) {
        self.binding_status = BindingStatus::Completed;
        self.updated_at = Utc::now();
    }

    /// 取消绑定
    pub fn cancel(&mut self) {
        self.is_active = false;
        self.binding_status = BindingStatus::Cancelled;
        self.updated_at = Utc::now();
    }

    /// 验证绑定数据
    pub fn validate(&self) -> Result<(), String> {
        if self.project_id.trim().is_empty() {
            return Err("项目ID不能为空".to_string());
        }

        if self.template_id.trim().is_empty() {
            return Err("模板ID不能为空".to_string());
        }

        if let Some(ref name) = self.binding_name {
            if name.len() > 100 {
                return Err("绑定名称不能超过100个字符".to_string());
            }
        }

        if let Some(ref desc) = self.description {
            if desc.len() > 500 {
                return Err("绑定描述不能超过500个字符".to_string());
            }
        }

        Ok(())
    }

    /// 获取绑定类型的显示名称
    pub fn get_binding_type_display(&self) -> &str {
        match self.binding_type {
            BindingType::Primary => "主要绑定",
            BindingType::Secondary => "次要绑定",
            BindingType::Reference => "参考绑定",
            BindingType::Test => "测试绑定",
        }
    }

    /// 获取绑定状态的显示名称
    pub fn get_binding_status_display(&self) -> &str {
        match self.binding_status {
            BindingStatus::Active => "活跃",
            BindingStatus::Paused => "暂停",
            BindingStatus::Completed => "已完成",
            BindingStatus::Cancelled => "已取消",
        }
    }

    /// 检查绑定是否可用
    pub fn is_available(&self) -> bool {
        self.is_active && matches!(self.binding_status, BindingStatus::Active)
    }
}

/// 创建项目-模板绑定请求模型
#[derive(Debug, Deserialize)]
pub struct CreateProjectTemplateBindingRequest {
    pub project_id: String,
    pub template_id: String,
    pub binding_name: Option<String>,
    pub description: Option<String>,
    pub priority: Option<u32>,
    pub binding_type: BindingType,
}

impl CreateProjectTemplateBindingRequest {
    pub fn validate(&self) -> Result<(), String> {
        if self.project_id.trim().is_empty() {
            return Err("项目ID不能为空".to_string());
        }

        if self.template_id.trim().is_empty() {
            return Err("模板ID不能为空".to_string());
        }

        if let Some(ref name) = self.binding_name {
            if name.len() > 100 {
                return Err("绑定名称不能超过100个字符".to_string());
            }
        }

        if let Some(ref desc) = self.description {
            if desc.len() > 500 {
                return Err("绑定描述不能超过500个字符".to_string());
            }
        }

        Ok(())
    }
}

/// 更新项目-模板绑定请求模型
#[derive(Debug, Deserialize)]
pub struct UpdateProjectTemplateBindingRequest {
    pub binding_name: Option<String>,
    pub description: Option<String>,
    pub priority: Option<u32>,
    pub binding_type: Option<BindingType>,
    pub binding_status: Option<BindingStatus>,
    pub is_active: Option<bool>,
}

impl UpdateProjectTemplateBindingRequest {
    pub fn validate(&self) -> Result<(), String> {
        if let Some(ref name) = self.binding_name {
            if name.len() > 100 {
                return Err("绑定名称不能超过100个字符".to_string());
            }
        }

        if let Some(ref desc) = self.description {
            if desc.len() > 500 {
                return Err("绑定描述不能超过500个字符".to_string());
            }
        }

        Ok(())
    }
}

/// 项目-模板绑定查询参数
#[derive(Debug, Deserialize)]
pub struct ProjectTemplateBindingQueryParams {
    pub project_id: Option<String>,
    pub template_id: Option<String>,
    pub binding_type: Option<BindingType>,
    pub binding_status: Option<BindingStatus>,
    pub is_active: Option<bool>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// 批量创建项目-模板绑定请求
#[derive(Debug, Deserialize)]
pub struct BatchCreateProjectTemplateBindingRequest {
    pub project_id: String,
    pub template_ids: Vec<String>,
    pub binding_type: BindingType,
    pub priority_start: Option<u32>, // 起始优先级，后续模板优先级递增
}

/// 批量删除项目-模板绑定请求
#[derive(Debug, Deserialize)]
pub struct BatchDeleteProjectTemplateBindingRequest {
    pub binding_ids: Vec<String>,
}

/// 项目-模板绑定详细信息（包含关联的项目和模板信息）
#[derive(Debug, Serialize)]
pub struct ProjectTemplateBindingDetail {
    pub binding: ProjectTemplateBinding,
    pub project_name: String,
    pub template_name: String,
    pub template_description: Option<String>,
}
