//
//  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
    }
}


