import Foundation

enum BookStackError: LocalizedError, Sendable {
    case invalidURL
    case notAuthenticated
    case unauthorized
    case forbidden
    case notFound(resource: String)
    case httpError(statusCode: Int, message: String?)
    case decodingError(String)
    case networkUnavailable
    case keychainError(OSStatus)
    case sslError
    case timeout
    case notReachable(host: String)
    case notBookStack(host: String)
    case unknown(String)

    var errorDescription: String? {
        switch self {
        case .invalidURL:
            return "The server URL is invalid. Make sure it starts with https://."
        case .notAuthenticated:
            return "Please sign in to continue. Go to Settings to reconnect."
        case .unauthorized:
            return "Invalid Token ID or Secret. Double-check both values — the secret is only shown once in BookStack."
        case .forbidden:
            return "Access denied. Either your account lacks the \"Access System API\" role permission, or your reverse proxy (nginx/Caddy) is not forwarding the Authorization header. Add `proxy_set_header Authorization $http_authorization;` to your proxy config."
        case .notFound(let resource):
            return "\(resource) could not be found. It may have been deleted or moved."
        case .httpError(let code, let message):
            return message ?? "Server returned error \(code). Check your server URL and try again."
        case .decodingError(let detail):
            return "Unexpected response from server. The BookStack version may not be compatible. (\(detail))"
        case .networkUnavailable:
            return "No internet connection. Showing cached content."
        case .keychainError(let status):
            return "Credential storage failed (code \(status))."
        case .sslError:
            return "SSL certificate error. If your server uses a self-signed certificate, contact your admin to install a trusted certificate."
        case .timeout:
            return "Request timed out. Make sure your device can reach the server."
        case .notReachable(let host):
            return "Could not reach \(host). Make sure the URL is correct and the server is running."
        case .notBookStack(let host):
            return "\(host) does not appear to be a BookStack server. Check the URL and try again."
        case .unknown(let msg):
            return msg
        }
    }
}
