import type { AccessRequest, CreateAccessRequestCommand } from "../../entities/access-request/types";

export interface CreateAccessRequestResponse {
  accessRequest: AccessRequest;
}

export async function createAccessRequest(command: CreateAccessRequestCommand): Promise<CreateAccessRequestResponse> {
  return requestJson<CreateAccessRequestResponse>("/api/access-requests", {
    method: "POST",
    body: JSON.stringify(command),
  });
}

async function requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);

  if (!headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(url, {
    ...init,
    headers,
  });

  if (!response.ok) {
    throw new Error(await readErrorMessage(response));
  }

  return (await response.json()) as T;
}

async function readErrorMessage(response: Response) {
  try {
    const payload = (await response.json()) as { error?: string };
    return payload.error ?? response.statusText;
  } catch {
    return response.statusText;
  }
}
