//! 设备信息数据结构

use serde::{Deserialize, Serialize};

/// 设备能力枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DeviceCapability {
    /// 文本消息
    Text,
    /// 图片消息
    Image,
    /// 文件传输
    File,
}

/// 设备信息结构
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceInfo {
    /// 设备唯一标识符 (UUID)
    pub device_id: String,
    /// 设备名称
    pub device_name: String,
    /// IP 地址
    pub ip: String,
    /// WebSocket 端口
    pub ws_port: u16,
    /// HTTP 端口
    pub http_port: u16,
    /// 是否在线
    pub online: bool,
    /// 设备能力列表
    pub capabilities: Vec<DeviceCapability>,
    /// 最后活跃时间戳 (Unix timestamp)
    #[serde(default)]
    pub last_seen: i64,
}

impl DeviceInfo {
    /// 创建新的设备信息
    pub fn new(
        device_id: String,
        device_name: String,
        ip: String,
        ws_port: u16,
        http_port: u16,
    ) -> Self {
        Self {
            device_id,
            device_name,
            ip,
            ws_port,
            http_port,
            online: true,
            capabilities: vec![
                DeviceCapability::Text,
                DeviceCapability::Image,
                DeviceCapability::File,
            ],
            last_seen: chrono::Utc::now().timestamp(),
        }
    }

    /// 获取 WebSocket 地址
    pub fn ws_addr(&self) -> String {
        format!("wss://{}:{}", self.ip, self.ws_port)
    }

    /// 获取 HTTP 地址
    pub fn http_addr(&self) -> String {
        format!("https://{}:{}", self.ip, self.http_port)
    }

    /// 更新最后活跃时间
    pub fn touch(&mut self) {
        self.last_seen = chrono::Utc::now().timestamp();
        self.online = true;
    }
}

/// UDP 广播发现数据包
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiscoveryPacket {
    /// 协议版本
    pub version: u8,
    /// 设备信息
    pub device: DeviceInfo,
    /// 数据包类型
    pub packet_type: DiscoveryPacketType,
}

/// 发现数据包类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DiscoveryPacketType {
    /// 广播通告
    Announce,
    /// 查询请求
    Query,
    /// 查询响应
    Response,
    /// 离线通知
    Goodbye,
}

impl DiscoveryPacket {
    /// 创建通告数据包
    pub fn announce(device: DeviceInfo) -> Self {
        Self {
            version: 1,
            device,
            packet_type: DiscoveryPacketType::Announce,
        }
    }

    /// 创建离线数据包
    pub fn goodbye(device: DeviceInfo) -> Self {
        Self {
            version: 1,
            device,
            packet_type: DiscoveryPacketType::Goodbye,
        }
    }

    /// 创建查询数据包
    pub fn query(device: DeviceInfo) -> Self {
        Self {
            version: 1,
            device,
            packet_type: DiscoveryPacketType::Query,
        }
    }
}
