import { SERVER_URL } from "./constants";

export type Tenant = {
  id: number;
  code: string;
  name: string;
  welcomeMessage: string;
  font: string | null;
  logo?: { id: number; base64Logo: string | null } | null;
};

export type Branch = {
  id: number;
  name: string;
  tellerStations: { id: number; name: string }[];
};

export type Service = {
  id: number;
  name: string;
};

export type Ticket = {
  id: number;
  number: string;
  createdAt: string;
  service: Service;
  branch: Branch;
  station: { id: number; name: string } | null;
};

export type TicketResponse = {
  ticket: Ticket;
  stations: { id: number; name: string }[];
};

async function request<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(`${SERVER_URL}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      ...(init?.headers ?? {}),
    },
  });

  if (!response.ok) {
    throw new Error(`Request failed (${response.status}) for ${path}`);
  }

  return response.json() as Promise<T>;
}

export function getTenant(code: string) {
  return request<Tenant>(`/api/v1/tenants/${encodeURIComponent(code)}`);
}

export function getBranches(tenantCode: string) {
  return request<Branch[]>(
    `/api/v1/branches/${encodeURIComponent(tenantCode)}`
  );
}

export function getBranchServices(tenantCode: string, branchId: number) {
  return request<Service[]>(
    `/api/v1/branches/${encodeURIComponent(tenantCode)}/${branchId}/services`
  );
}

export function createTicket(input: {
  branchId: number;
  serviceId: number;
  deviceToken: string;
}) {
  return request<TicketResponse>("/api/v1/tickets", {
    method: "POST",
    body: JSON.stringify(input),
  });
}

export function getTicketById(ticketId: number | string) {
  return request<Ticket>(`/api/v1/tickets/${ticketId}`);
}

export function getTicketsForDevice(deviceToken: string) {
  return request<TicketResponse[]>(
    `/api/v1/tickets/devices/${encodeURIComponent(deviceToken)}`
  );
}
