import {
  ConflictException,
  BadRequestException,
  NotFoundException,
  ForbiddenException,
  UnauthorizedException,
} from "@nestjs/common";
import { extractErrorMessage } from "@bff/core/utils/error.util.js";

export enum ErrorCategory {
  /** Network timeout, rate limit — "Try again in a moment" */
  RETRIABLE = "RETRIABLE",
  /** Email already registered, invalid data — specific message */
  PERMANENT = "PERMANENT",
  /** SF down, WHMCS unavailable — "We're having issues, try later" */
  TRANSIENT = "TRANSIENT",
}

export interface ClassifiedError {
  errorCategory: ErrorCategory;
  message: string;
}

/**
 * Classify an error into a category for the frontend.
 *
 * - ConflictException / BadRequestException / ForbiddenException / UnauthorizedException → PERMANENT
 * - Timeout / ECONNREFUSED / rate-limit → RETRIABLE
 * - Everything else → TRANSIENT
 */
export function classifyError(error: unknown): ClassifiedError {
  // Permanent: business-rule violations the user can't retry past
  if (
    error instanceof ConflictException ||
    error instanceof BadRequestException ||
    error instanceof ForbiddenException ||
    error instanceof UnauthorizedException ||
    error instanceof NotFoundException
  ) {
    return {
      errorCategory: ErrorCategory.PERMANENT,
      message: extractErrorMessage(error),
    };
  }

  const msg = extractErrorMessage(error).toLowerCase();

  // Retriable: transient network issues the user can try again
  if (
    msg.includes("timeout") ||
    msg.includes("econnrefused") ||
    msg.includes("econnreset") ||
    msg.includes("rate limit") ||
    msg.includes("too many requests") ||
    msg.includes("429")
  ) {
    return {
      errorCategory: ErrorCategory.RETRIABLE,
      message: "A temporary error occurred. Please try again in a moment.",
    };
  }

  // Default: infrastructure issues
  return {
    errorCategory: ErrorCategory.TRANSIENT,
    message: "We're experiencing technical difficulties. Please try again later.",
  };
}
