// ER / TypeScript server-side example.
// Keep USHS_API_TOKEN in environment variables. Do not expose it in browser code.

const USHS_API_BASE = process.env.USHS_API_BASE ?? 'https://yourdomain.com/ushs/api/v1';
const USHS_API_TOKEN = process.env.USHS_API_TOKEN ?? '';

async function ushsFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(`${USHS_API_BASE}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${USHS_API_TOKEN}`,
      'Content-Type': 'application/json',
      ...(init.headers ?? {}),
    },
  });

  const data = await res.json();
  if (!res.ok || data.success === false) {
    throw new Error(data.message || `USHS API error ${res.status}`);
  }
  return data as T;
}

export async function listUshsTickets() {
  return ushsFetch('/tickets.php?action=list&source_system=all');
}

export async function importErTicketToPhp(ticket: {
  er_ticket_id: string;
  request_number: string;
  full_name: string;
  phone_number: string;
  customer_email?: string;
  service_address: string;
  zip_code: string;
  issue_description?: string;
  status_id?: number;
}) {
  return ushsFetch('/tickets.php?action=create', {
    method: 'POST',
    body: JSON.stringify({
      ...ticket,
      source_system: 'typescript_er',
      origin_type: 'ER Ticket',
    }),
  });
}

export async function updatePhpTicketFromEr(id: number, patch: Record<string, unknown>) {
  return ushsFetch(`/tickets.php?action=update&id=${id}`, {
    method: 'PATCH',
    body: JSON.stringify(patch),
  });
}

export async function deletePhpTicket(id: number) {
  return ushsFetch(`/tickets.php?action=delete&id=${id}`, {
    method: 'DELETE',
  });
}
