import axios from "axios";

/**
 * Shared error handler for MCP tool responses.
 * Extracts structured error messages from backend API responses
 * while preventing token/internal URL leakage.
 */
export function errorResponse(err: unknown) {
  let message = "An unexpected error occurred";

  if (axios.isAxiosError(err)) {
    // Extract structured error from backend ApiResponse
    const apiError =
      err.response?.data?.error?.message ??
      err.response?.data?.error ??
      err.response?.data?.Message ??
      err.response?.data?.title;

    if (apiError && typeof apiError === "string") {
      message = apiError;
    } else if (err.response?.status === 401) {
      message = "Authentication failed — API token may be expired. Update API_TOKEN in .env";
    } else if (err.response?.status === 403) {
      message = "Access denied — insufficient permissions for this operation";
    } else if (err.response?.status === 404) {
      message = "Resource not found";
    } else if (err.response?.status === 400) {
      message = `Bad request: ${JSON.stringify(err.response?.data?.errors ?? err.response?.data) ?? "invalid input"}`;
    } else if (err.code === "ECONNREFUSED" || err.code === "ECONNRESET") {
      message = "Service unavailable — check that Docker services are running";
    } else if (err.code === "ETIMEDOUT" || err.code === "ECONNABORTED") {
      message = "Request timed out — service may be under heavy load";
    } else {
      // Fallback: use status text, never raw error.message (may contain internal URLs/tokens)
      message = `Request failed with status ${err.response?.status ?? "unknown"}`;
    }
  } else if (err instanceof Error) {
    message = err.message;
  }

  return {
    content: [{ type: "text" as const, text: `Error: ${message}` }],
    isError: true,
  };
}

export function textResponse(text: string) {
  return { content: [{ type: "text" as const, text }] };
}
