//
//  APIEnvironment.swift
//  suixinkan
//

import Foundation

/// 网络环境实体，集中描述 HTTP 和 WebSocket 的服务地址。
struct APIEnvironment: Equatable {
    let baseURL: URL
    let webSocketURL: URL

    nonisolated static let production = APIEnvironment(
        baseURL: URL(string: "https://api.zhifly.cn")!,
        webSocketURL: URL(string: "wss://api.zhifly.cn/wss")!
    )

    nonisolated static let testing = APIEnvironment(
        baseURL: URL(string: "https://api-test.zhifly.cn")!,
        webSocketURL: URL(string: "wss://api-test.zhifly.cn/wss")!
    )

    nonisolated static var current: APIEnvironment {
        #if DEBUG
        .testing
        #else
        .production
        #endif
    }
}

/// 客户端信息工具，负责提供网络请求所需的 App 版本和系统类型。
enum AppClientInfo {
    nonisolated static let osType = "iOS"

    /// 生成后端要求的 App 版本号，版本号不足三段时用 build 号补齐。
    nonisolated static func appVersion(infoDictionary: [String: Any]? = Bundle.main.infoDictionary) -> String {
        let version = (infoDictionary?["CFBundleShortVersionString"] as? String)?
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .nonEmpty ?? "1.0.0"
        let build = (infoDictionary?["CFBundleVersion"] as? String)?
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .nonEmpty
        let versionParts = version.split(separator: ".", omittingEmptySubsequences: false)

        if versionParts.count >= 3 {
            return version
        }
        if versionParts.count == 2, let build {
            return "\(version).\(build)"
        }
        return version
    }
}

private extension String {
    nonisolated var nonEmpty: String? {
        isEmpty ? nil : self
    }
}
