//
//  CustomError.swift
//  Nextcloud Cookbook iOS Client
//
//  Created by Vincent Meilinger on 13.09.23.
//

import Foundation

public enum NetworkError: Error, LocalizedError {
    case missingUrl
    case encodingFailed(detail: String? = nil)
    case decodingFailed(detail: String? = nil)
    case httpError(statusCode: Int, body: String? = nil)
    case connectionError(underlying: Error? = nil)
    case invalidRequest
    case unknownError(detail: String? = nil)

    public var errorDescription: String? {
        switch self {
        case .missingUrl:
            return "Missing URL."
        case .encodingFailed(let detail):
            return "Parameter encoding failed." + (detail.map { " \($0)" } ?? "")
        case .decodingFailed(let detail):
            return "Data decoding failed." + (detail.map { " \($0)" } ?? "")
        case .httpError(let statusCode, let body):
            return "HTTP error \(statusCode)." + (body.map { " \($0)" } ?? "")
        case .connectionError(let underlying):
            return "Connection error." + (underlying.map { " \($0.localizedDescription)" } ?? "")
        case .invalidRequest:
            return "Invalid request."
        case .unknownError(let detail):
            return "Unknown error." + (detail.map { " \($0)" } ?? "")
        }
    }

    var isClientError: Bool {
        if case .httpError(let statusCode, _) = self {
            return (400...499).contains(statusCode)
        }
        return false
    }

    var isServerError: Bool {
        if case .httpError(let statusCode, _) = self {
            return (500...599).contains(statusCode)
        }
        return false
    }
}
