//! 通用类型定义

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

/// 设备ID (9位数字格式，如 732 940 272)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct DeviceId(pub String);

impl DeviceId {
    /// 生成新的设备ID
    pub fn generate() -> Self {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        let id: u32 = rng.gen_range(100_000_000..999_999_999);
        Self(format!("{}", id))
    }

    /// 格式化显示 (如: 732 940 272)
    pub fn formatted(&self) -> String {
        let s = &self.0;
        if s.len() == 9 {
            format!("{} {} {}", &s[0..3], &s[3..6], &s[6..9])
        } else {
            s.clone()
        }
    }

    /// 从字符串解析
    pub fn from_string(s: &str) -> Self {
        // 移除空格
        Self(s.replace(' ', ""))
    }
}

impl std::fmt::Display for DeviceId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.formatted())
    }
}

/// 验证码 (8位随机字符)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationCode(pub String);

impl VerificationCode {
    /// 生成新的验证码
    pub fn generate() -> Self {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        let code: String = (0..8)
            .map(|_| {
                let idx = rng.gen_range(0..36);
                if idx < 10 {
                    (b'0' + idx) as char
                } else {
                    (b'a' + idx - 10) as char
                }
            })
            .collect();
        Self(code)
    }

    /// 刷新验证码
    pub fn refresh(&mut self) {
        *self = Self::generate();
    }
}

impl std::fmt::Display for VerificationCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// 用户信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub id: Uuid,
    pub username: String,
    pub email: Option<String>,
    pub created_at: DateTime<Utc>,
    pub last_login: Option<DateTime<Utc>>,
}

/// 设备信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Device {
    pub id: Uuid,
    pub device_id: DeviceId,
    pub name: String,
    pub os_type: OsType,
    pub os_version: String,
    pub user_id: Option<Uuid>,
    pub is_online: bool,
    pub allow_remote: bool,
    pub last_seen: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
}

/// 操作系统类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum OsType {
    Windows,
    MacOS,
    Linux,
    Android,
    IOS,
    Unknown,
}

impl OsType {
    pub fn current() -> Self {
        #[cfg(target_os = "windows")]
        return OsType::Windows;
        #[cfg(target_os = "macos")]
        return OsType::MacOS;
        #[cfg(target_os = "linux")]
        return OsType::Linux;
        #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
        return OsType::Unknown;
    }
}

/// 连接会话
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub id: Uuid,
    pub controller_device_id: DeviceId,
    pub controlled_device_id: DeviceId,
    pub started_at: DateTime<Utc>,
    pub ended_at: Option<DateTime<Utc>>,
    pub connection_type: ConnectionType,
    pub status: SessionStatus,
}

/// 连接类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ConnectionType {
    /// P2P直连
    P2P,
    /// 服务器中转
    Relay,
}

/// 会话状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SessionStatus {
    /// 连接中
    Connecting,
    /// 已连接
    Connected,
    /// 已断开
    Disconnected,
    /// 连接失败
    Failed,
}

/// 控制历史记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ControlHistory {
    pub id: Uuid,
    pub user_id: Option<Uuid>,
    pub controller_device_id: DeviceId,
    pub controlled_device_id: DeviceId,
    pub controlled_device_name: String,
    pub started_at: DateTime<Utc>,
    pub ended_at: Option<DateTime<Utc>>,
    pub duration_seconds: Option<i64>,
    pub connection_type: ConnectionType,
}

/// 质量设置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualitySettings {
    /// 帧率 (fps)
    pub frame_rate: u32,
    /// 分辨率缩放比例 (0.25 - 1.0)
    pub resolution_scale: f32,
    /// 图像质量 (1-100)
    pub image_quality: u32,
    /// 是否启用硬件加速
    pub hardware_acceleration: bool,
}

impl Default for QualitySettings {
    fn default() -> Self {
        Self {
            frame_rate: 30,
            resolution_scale: 1.0,
            image_quality: 80,
            hardware_acceleration: true,
        }
    }
}

/// 登录请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginRequest {
    pub username: String,
    pub password: String,
    pub device_id: DeviceId,
}

/// 登录响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginResponse {
    pub token: String,
    pub user: User,
    pub devices: Vec<Device>,
}

/// 注册请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterRequest {
    pub username: String,
    pub password: String,
    pub email: Option<String>,
}
