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

export class NetworkExceptionHandler {
  static canHandle(error: unknown): error is Error | DOMException {
    if (!isErrorLike(error)) return false;
    const message = error.message.toLowerCase();
    return (
      error.name === "AbortError" ||
      error.name === "TimeoutError" ||
      message.includes("failed to fetch") ||
      message.includes("fetch failed") ||
      message.includes("network") ||
      message.includes("timeout")
    );
  }

  static handle(error: Error | DOMException): ExceptionResult {
    if (error.name === "AbortError") {
      return {
        code: ExceptionCode.cancelled,
        message: "Request cancelled.",
      };
    }

    const message = error.message.toLowerCase();
    if (error.name === "TimeoutError" || message.includes("timeout")) {
      return {
        code: ExceptionCode.timeout,
        message: "Request timeout, please try again.",
      };
    }

    return {
      code: ExceptionCode.network,
      message: "Network connection failed.",
    };
  }
}

function isErrorLike(error: unknown): error is Error | DOMException {
  if (error instanceof Error) return true;
  return typeof DOMException !== "undefined" && error instanceof DOMException;
}
