import type { z } from "zod/v4"; import { CompaniesResponseSchema, CompanyErrorResponseSchema, CompanyResponseSchema, } from "../../common"; export const companyKeys = { all: ["companies"], list: ["companies", "list"], detail: (id: string) => ["companies", "detail", id], }; export class CompanyApiError extends Error { constructor(public readonly code: string) { super(code); } } export async function companyRequest( path: string, schema: z.ZodType, body?: unknown, csrfToken?: string ): Promise { const response = await fetch(`/api/companies${path}`, { method: body === undefined ? "GET" : "POST", credentials: "same-origin", headers: body === undefined ? {} : { "content-type": "application/json", "x-csrf-token": csrfToken ?? "" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); const json: unknown = await response.json(); if (!response.ok) { const error = CompanyErrorResponseSchema.safeParse(json); throw new CompanyApiError(error.success ? error.data.code : "INTERNAL_ERROR"); } return schema.parse(json); } export const companyApi = { list: () => companyRequest("", CompaniesResponseSchema), get: (id: string) => companyRequest(`/${id}`, CompanyResponseSchema), save: (id: string | undefined, body: unknown, token: string) => companyRequest(id ? `/${id}/update` : "", CompanyResponseSchema, body, token), contact: (companyId: string, id: string | undefined, body: unknown, token: string) => companyRequest( `/${companyId}/contacts${id ? `/${id}/update` : ""}`, CompanyResponseSchema, body, token ), site: (companyId: string, id: string | undefined, body: unknown, token: string) => companyRequest( `/${companyId}/sites${id ? `/${id}/update` : ""}`, CompanyResponseSchema, body, token ), };