import type { ApiErrorResponse } from "@/types";
import i18n from "@/lib/i18n";

export class ApiError extends Error {
  public status: number;
  public code: string;
  public fieldErrors?: Record<string, string[]>;
  public requestId?: string;

  constructor(status: number, response: ApiErrorResponse) {
    super(response.detail || i18n.t('lib.errors.text_1'));
    this.name = "ApiError";
    this.status = status;
    this.code = response.code || "UNKNOWN_ERROR";
    this.fieldErrors = response.field_errors;
    this.requestId = response.request_id;

    // Maintain proper stack trace in V8 (Node/Chrome/Next.js)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ApiError);
    }
  }

  /**
   * Helper to determine if this is a validation error (FastAPI 422 Unprocessable Entity)
   */
  isValidationError(): boolean {
    return this.status === 422;
  }

  /**
   * Helper to determine if the session expired (401 Unauthorized)
   */
  isUnauthorized(): boolean {
    return this.status === 401;
  }

  /**
   * Helper to determine if permission is denied (403 Forbidden)
   */
  isForbidden(): boolean {
    return this.status === 403;
  }
}

/**
   * Formats a generic error or native error into an ApiError format
   */
export function handleApiError(error: unknown): ApiError {
  if (error instanceof ApiError) {
    return error;
  }

  const genericResponse: ApiErrorResponse = {
    detail: error instanceof Error ? error.message : i18n.t('lib.errors.text_2'),
    code: "NETWORK_ERROR",
  };

  return new ApiError(500, genericResponse);
}
