import { ApiHttpError, ApiTimeoutError } from "@/shared/api/errors";

export interface ErrorResponse {
  status: 404 | 500 | 503;
  headers?: Record<string, string>;
  errorCode: "not_found" | "internal" | "unavailable";
}

/**
 * Maps an application error to a structured HTTP-like response.
 * Consumed by SSR loader paths and error page routing.
 *
 * Mapping rules (design spec S4.6):
 * - ApiHttpError 404       -> { status: 404, errorCode: "not_found" }
 * - ApiHttpError 500-599   -> { status: 500, errorCode: "internal" }
 * - ApiTimeoutError        -> { status: 503, Retry-After: 30, errorCode: "unavailable" }
 * - Everything else        -> { status: 500, errorCode: "internal" }
 */
export function errorToResponse(error: unknown): ErrorResponse {
  if (error instanceof ApiHttpError) {
    if (error.status === 404) {
      return { status: 404, errorCode: "not_found" };
    }
    if (error.status >= 500 && error.status <= 599) {
      return { status: 500, errorCode: "internal" };
    }
    // Any other HTTP status (e.g. 403) falls through to the default
    return { status: 500, errorCode: "internal" };
  }

  if (error instanceof ApiTimeoutError) {
    return {
      status: 503,
      headers: { "Retry-After": "30" },
      errorCode: "unavailable",
    };
  }

  return { status: 500, errorCode: "internal" };
}
