import type { Prescription, PrescriptionDetail } from './prescriptions-types';

export class PrescriptionsClientError extends Error {
  constructor(message: string, readonly statusCode: number) {
    super(message);
    this.name = 'PrescriptionsClientError';
  }
}

async function handle<T>(res: Response): Promise<T> {
  const data = (await res.json().catch(() => null)) as
    | T
    | { message: string | string[] }
    | null;
  if (!res.ok) {
    const msg =
      (data as { message?: string | string[] } | null)?.message ??
      `Request failed (${res.status})`;
    throw new PrescriptionsClientError(
      Array.isArray(msg) ? msg.join('\n') : msg,
      res.status,
    );
  }
  return data as T;
}

export const prescriptionsClient = {
  async list(): Promise<Prescription[]> {
    const res = await fetch('/api/prescriptions', { cache: 'no-store' });
    return handle<Prescription[]>(res);
  },
  async get(id: string): Promise<PrescriptionDetail> {
    const res = await fetch(`/api/prescriptions/${id}`, { cache: 'no-store' });
    return handle<PrescriptionDetail>(res);
  },
  pdfUrl(id: string): string {
    return `/api/prescriptions/${id}/pdf`;
  },
};
