//
//  APIError.swift
//  suixinkan
//

import Foundation

/// 网络层错误实体，统一转换 URL、HTTP、业务码、解析和网络异常。
enum APIError: Error, LocalizedError {
    case invalidURL
    case invalidResponse
    case httpStatus(Int, String)
    case serverCode(Int, String)
    case emptyData
    case decodeFailed(String)
    case networkFailed(String)

    var errorDescription: String? {
        switch self {
        case .invalidURL:
            "请求地址无效"
        case .invalidResponse:
            "服务响应异常"
        case let .httpStatus(statusCode, message):
            "请求失败（HTTP \(statusCode)）：\(message)"
        case .serverCode(_, let message):
            message
        case .emptyData:
            "接口返回数据为空"
        case .decodeFailed(let message):
            "数据解析失败：\(message)"
        case .networkFailed(let message):
            "网络请求失败：\(message)"
        }
    }
}

extension APIError {
    /// 与 Android `NetworkResponse.isTokenFailed` 对齐的 Token 失效业务码。
    static let tokenInvalidCodes: Set<Int> = [180024, 100091, 100090, 100060]

    /// 判断任意错误是否代表登录凭证失效。
    static func isAuthenticationExpired(_ error: Error) -> Bool {
        guard let apiError = error as? APIError else { return false }
        switch apiError {
        case let .httpStatus(statusCode, _):
            return statusCode == 401 || statusCode == 403
        case let .serverCode(code, _):
            return tokenInvalidCodes.contains(code)
        default:
            return false
        }
    }
}
