/**
 * Client-side helper for posting a form payload to a Next.js Route Handler
 * and normalising the response. Used by the form components.
 */

export interface SubmitResponse {
  ok: boolean
  message?: string
  errors?: Record<string, string>
  alreadySubscribed?: boolean
}

export async function submitForm(
  url: string,
  payload: Record<string, unknown>,
): Promise<SubmitResponse> {
  try {
    const res = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    })

    let data: Partial<SubmitResponse> = {}
    try {
      data = (await res.json()) as Partial<SubmitResponse>
    } catch {
      // non-JSON response
    }

    return {
      ok: res.ok,
      message: data.message,
      errors: data.errors,
      alreadySubscribed: data.alreadySubscribed,
    }
  } catch {
    return { ok: false, message: "Network error. Please try again." }
  }
}
