import { ApiError, ErrorCode } from "@/data/services/api/api_result";

import { ExceptionCode } from "../exception-code";
import type { ExceptionResult } from "../exception-result";

export class ApiExceptionHandler {
  static canHandle(error: unknown): error is ApiError {
    return error instanceof ApiError;
  }

  static handle(error: ApiError): ExceptionResult {
    switch (error.status) {
      case ErrorCode.httpUnauthorized:
        return {
          code: ExceptionCode.unauthorized,
          message: "Session expired, please sign in again.",
        };
      case ErrorCode.httpForbidden:
        return {
          code: ExceptionCode.forbidden,
          message: "Access denied.",
        };
      case ErrorCode.httpNotFound:
        return {
          code: ExceptionCode.notFound,
          message: "Resource not found.",
        };
      case ErrorCode.httpServerError:
        return {
          code: ExceptionCode.server,
          message: "Server error, please try again later.",
        };
      default:
        return {
          code: mapApiCode(error.code),
          message: error.message || "API call failed.",
        };
    }
  }
}

function mapApiCode(code: string): ExceptionResult["code"] {
  switch (code) {
    case "HTTP_UNAUTHORIZED":
      return ExceptionCode.unauthorized;
    case "HTTP_SERVER_ERROR":
      return ExceptionCode.server;
    case ErrorCode.networkError:
      return ExceptionCode.network;
    case ErrorCode.timeoutError:
      return ExceptionCode.timeout;
    case ErrorCode.parseError:
      return ExceptionCode.validation;
    default:
      return ExceptionCode.unknown;
  }
}
