import type { ClientError } from "graphql-request";

export interface ApiErrorShape {
  message: string;
  details?: unknown;
}

export function normalizeError(err: unknown): ApiErrorShape {
  if (!err) return { message: "Unknown error" };
  if (typeof err === "string") return { message: err };
  if (err instanceof Error) {
    return { message: err.message };
  }
  return { message: "Unexpected error", details: err };
}

// Minimal subset of Express' Response to avoid importing full types repeatedly
interface MinimalResponse {
  status(code: number): this;
  json(body: unknown): this;
}

export function respondWithError(
  res: MinimalResponse,
  err: unknown,
  fallback = "Request failed"
) {
  const normalized = normalizeError(err);
  res.status(500).json({ message: fallback, error: normalized.message });
}

export function isClientError(err: unknown): err is ClientError {
  return (
    !!err && typeof err === "object" && "response" in err && "request" in err
  );
}

// Enhanced normalize after adding ClientError helper (placed after respond function to reuse normalizeError definition order remains valid)
export function enhancedNormalize(err: unknown): ApiErrorShape {
  if (isClientError(err)) {
    const ce = err as ClientError;
    interface GQLErrorLike {
      message: string;
    }
    const messages = ce.response.errors
      ?.map((e: GQLErrorLike) => e.message)
      .join("; ");
    return { message: messages || ce.message, details: ce.response.errors };
  }
  return normalizeError(err);
}
