// @File: src/lib/contact-api.ts
// @Desc: Thin fetch helpers for the public marketing-site contact forms.
//        These endpoints are public (no JWT required) and the backend relays
//        the submission to the correct DoItEasy inbox via SMTP.

export interface ContactFormPayload {
  name: string;
  email: string;
  phone?: string;
  subject?: string;
  message: string;
}

export interface GetPriceFormPayload {
  name: string;
  email: string;
  phone?: string;
  company?: string;
  service?: string;
  message?: string;
}

export interface SupportFormPayload {
  name: string;
  email: string;
  phone?: string;
  subject?: string;
  message: string;
}

export interface ContactFormResult {
  success: boolean;
  message: string;
}

async function postJson<T extends object>(
  path: string,
  payload: T,
): Promise<ContactFormResult> {
  let res: Response;
  try {
    res = await fetch(path, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      credentials: "omit",
    });
  } catch (err) {
    throw new Error(
      err instanceof Error
        ? `Network error: ${err.message}`
        : "Network error while sending your message.",
    );
  }

  let body: unknown = null;
  try {
    body = await res.json();
  } catch {
    // ignore – we'll fall back to status-based messaging below.
  }

  if (!res.ok) {
    const detail =
      (body && typeof body === "object" && "detail" in body
        ? (body as { detail?: string }).detail
        : undefined) ||
      (body && typeof body === "object" && "message" in body
        ? (body as { message?: string }).message
        : undefined);
    throw new Error(
      detail || `Request failed with status ${res.status}. Please try again.`,
    );
  }

  const ok = body && typeof body === "object" ? (body as ContactFormResult) : null;
  return {
    success: ok?.success ?? true,
    message: ok?.message ?? "Your message has been sent successfully.",
  };
}

export const submitContactForm = (payload: ContactFormPayload) =>
  postJson("/api/v1/contact/contact-us", payload);

export const submitGetPriceForm = (payload: GetPriceFormPayload) =>
  postJson("/api/v1/contact/get-price", payload);

export const submitSupportForm = (payload: SupportFormPayload) =>
  postJson("/api/v1/contact/support", payload);