import fetch from "node-fetch";

export interface BackendConfig {
  baseUrl: string; // no trailing slash, e.g. http://localhost:8001
  secret: string;
}

export interface PublishEventPayload {
  requestId: string;
  submittedByEmail: string;
  event: Record<string, unknown>;
}

export interface PublishResult {
  ok: boolean;
  status: number;
  body: unknown;
}

// Calls backend/'s POST /api/events/publish. The shared secret is the only
// thing authenticating this call -- it proves the request came from
// upstream/, not who the individual submitter is (that's carried inside
// the payload as submittedByEmail instead). backend/'s validateRequest.ts
// is the single source of truth for whether the payload itself is valid;
// this function doesn't duplicate that logic, just relays its response.
export async function publishEvent(config: BackendConfig, payload: PublishEventPayload): Promise<PublishResult> {
  const res = await fetch(`${config.baseUrl}/api/events/publish`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${config.secret}`,
    },
    body: JSON.stringify(payload),
  });
  const body = await res.json().catch(() => null);
  return { ok: res.ok, status: res.status, body };
}
