export interface TicketMessage {
  id: string;
  author: string;
  role: string;
  content: string;
  is_staff?: boolean;
  timestamp: string;
}

export interface SupportTicket {
  id: string;
  restaurantId: string;
  userId?: string;
  subject: string;
  description?: string;
  status: string;
  priority: string;
  messages: TicketMessage[];
  createdAt: string;
  updatedAt: string;
}

export interface TicketListResponse {
  tickets: SupportTicket[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function listTickets(params: Record<string, string> = {}): Promise<TicketListResponse> {
  const qs = new URLSearchParams(params).toString();
  return apiFetch<TicketListResponse>(`/api/support-tickets${qs ? '?' + qs : ''}`);
}

export async function getTicket(id: string): Promise<{ ticket: SupportTicket }> {
  return apiFetch<{ ticket: SupportTicket }>(`/api/support-tickets/${id}`);
}

export async function createTicket(body: Record<string, unknown>): Promise<{ ticket: SupportTicket }> {
  return apiFetch<{ ticket: SupportTicket }>('/api/support-tickets', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function updateTicket(id: string, body: Record<string, unknown>): Promise<{ ticket: SupportTicket }> {
  return apiFetch<{ ticket: SupportTicket }>(`/api/support-tickets/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function deleteTicket(id: string): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>(`/api/support-tickets/${id}`, { method: 'DELETE' });
}
