//
//  PhoneConfig.swift
//  JJPhoneDemo
//
//

import Foundation

/// 电话配置管理类
/// 用于管理账号、密码和环境配置
class PhoneConfig {
    
    static let shared = PhoneConfig()
    
    private let passwordService = "JJPhoneDemo.PhoneConfig"
    private let passwordAccount = "sipPassword"
    
    /// 登录账号
    var account: String {
        get { UserDefaults.standard.string(forKey: "PhoneConfig.account") ?? "" }
        set { UserDefaults.standard.set(newValue, forKey: "PhoneConfig.account") }
    }
    
    /// 登录密码
    var password: String {
        get {
            // 1. 优先从 Keychain 读取
            if let keychainValue = KeychainHelper.getPassword(service: passwordService, account: passwordAccount) {
                return keychainValue
            }
            // 2. 兼容旧版本：从 UserDefaults 迁移一次到 Keychain
            if let legacy = UserDefaults.standard.string(forKey: "PhoneConfig.password"), !legacy.isEmpty {
                _ = KeychainHelper.setPassword(legacy, service: passwordService, account: passwordAccount)
                UserDefaults.standard.removeObject(forKey: "PhoneConfig.password")
                return legacy
            }
            return ""
        }
        set {
            if newValue.isEmpty {
                // 清空密码
                KeychainHelper.deletePassword(service: passwordService, account: passwordAccount)
                UserDefaults.standard.removeObject(forKey: "PhoneConfig.password")
            } else {
                _ = KeychainHelper.setPassword(newValue, service: passwordService, account: passwordAccount)
                // 为了兼容旧版本，确保不再保留明文密码
                UserDefaults.standard.removeObject(forKey: "PhoneConfig.password")
            }
        }
    }
    
    /// 服务器环境（用于完整登录流程）
    var environment: VoIPEnvironment {
        get {
            let rawValue = UserDefaults.standard.integer(forKey: "PhoneConfig.environment")
            // VoIPEnvironment 是从 Objective-C 导入的枚举
            if rawValue == 0 {
                return .production
            } else {
                return .development
            }
        }
        set {
            UserDefaults.standard.set(newValue.rawValue, forKey: "PhoneConfig.environment")
        }
    }
    
    private init() {}
    
    /// 重置为默认配置
    func resetToDefaults() {
        UserDefaults.standard.removeObject(forKey: "PhoneConfig.account")
        KeychainHelper.deletePassword(service: passwordService, account: passwordAccount)
        UserDefaults.standard.removeObject(forKey: "PhoneConfig.password")
        UserDefaults.standard.removeObject(forKey: "PhoneConfig.environment")
    }
    
    /// 检查配置是否完整
    func isConfigured() -> Bool {
        return !account.isEmpty && !password.isEmpty
    }

    // MARK: - 外呼 OpenAPI（openapi.useasy.cn）

    /// 默认外呼配置（未单独设置时使用）
    private static let defaultCalloutAppId = "1019"
    private static let defaultCalloutSecretKey = "E91AB02B1FF441D88E305E8E287A6B7D"
    private static let defaultCalloutAgentNumber = "6101"
    private static let defaultCalloutCustomerNumber = "13522125542"

    /// 外呼接口账户编号（appid），未设置时使用默认 1019
    var calloutAppId: String {
        get {
            let stored = UserDefaults.standard.string(forKey: "PhoneConfig.calloutAppId")
            if let s = stored, !s.isEmpty { return s }
            return Self.defaultCalloutAppId
        }
        set { UserDefaults.standard.set(newValue, forKey: "PhoneConfig.calloutAppId") }
    }

    /// 外呼接口密钥（secretKey），未设置时使用默认密钥
    var calloutSecretKey: String {
        get {
            let stored = UserDefaults.standard.string(forKey: "PhoneConfig.calloutSecretKey")
            if let s = stored, !s.isEmpty { return s }
            return Self.defaultCalloutSecretKey
        }
        set { UserDefaults.standard.set(newValue, forKey: "PhoneConfig.calloutSecretKey") }
    }

    /// 默认座席工号，未设置时使用 6100
    var calloutAgentNumber: String {
        get {
            let stored = UserDefaults.standard.string(forKey: "PhoneConfig.calloutAgentNumber")
            if let s = stored, !s.isEmpty { return s }
            return Self.defaultCalloutAgentNumber
        }
        set { UserDefaults.standard.set(newValue, forKey: "PhoneConfig.calloutAgentNumber") }
    }

    /// 默认被叫号码，未设置时使用 13522125542
    var calloutCustomerNumber: String {
        get {
            let stored = UserDefaults.standard.string(forKey: "PhoneConfig.calloutCustomerNumber")
            if let s = stored, !s.isEmpty { return s }
            return Self.defaultCalloutCustomerNumber
        }
        set { UserDefaults.standard.set(newValue, forKey: "PhoneConfig.calloutCustomerNumber") }
    }

    /// 外呼是否已配置（始终有默认 appId/secretKey，恒为 true；若需“仅用户配置”可再加标志位）
    var isCalloutConfigured: Bool {
        return true
    }
}


