export interface Customer {
  id: string;
  restaurantId: string;
  name: string;
  email?: string;
  phone?: string;
  totalOrders: number;
  totalSpend: number;
  totalReservations: number;
  totalVisits: number;
  lastVisit?: string;
  notes?: string;
  preferences?: string[];
  tags?: string[];
  createdAt: string;
  updatedAt: string;
}

export interface CustomerListResponse {
  customers: Customer[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

export function normalizeCustomer(raw: Record<string, unknown>): Customer {
  return {
    id: String(raw.id ?? ''),
    restaurantId: String(raw.restaurant_id ?? raw.restaurantId ?? ''),
    name: String(raw.name ?? ''),
    email: raw.email != null ? String(raw.email) : undefined,
    phone: raw.phone != null ? String(raw.phone) : undefined,
    totalOrders: Number(raw.total_orders ?? raw.totalOrders ?? 0),
    totalSpend: Number(raw.computed_spend ?? raw.total_spend ?? raw.totalSpend ?? 0),
    totalReservations: Number(raw.total_reservations ?? raw.totalReservations ?? 0),
    totalVisits: Number(raw.total_visits ?? raw.totalVisits ?? 0),
    lastVisit: raw.last_visit != null ? String(raw.last_visit) : undefined,
    notes: raw.notes != null ? String(raw.notes) : undefined,
    preferences: Array.isArray(raw.preferences) ? raw.preferences.map(String) : [],
    tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],
    createdAt: String(raw.created_at ?? raw.createdAt ?? ''),
    updatedAt: String(raw.updated_at ?? raw.updatedAt ?? ''),
  };
}

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 listCustomers(params: Record<string, string> = {}): Promise<CustomerListResponse> {
  const qs = new URLSearchParams(params).toString();
  const raw = await apiFetch<{ customers: Record<string, unknown>[]; total: number; page: number; limit: number; pages: number }>(`/api/customers${qs ? '?' + qs : ''}`);
  return {
    customers: (raw.customers ?? []).map(normalizeCustomer),
    total: raw.total,
    page: raw.page,
    limit: raw.limit,
    pages: raw.pages,
  };
}

export async function getCustomer(id: string): Promise<{ customer: Customer }> {
  const raw = await apiFetch<{ customer: Record<string, unknown> }>(`/api/customers/${id}`);
  return { customer: normalizeCustomer(raw.customer) };
}

export async function createCustomer(body: Record<string, unknown>): Promise<{ customer: Customer }> {
  const raw = await apiFetch<{ customer: Record<string, unknown> }>('/api/customers', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { customer: normalizeCustomer(raw.customer) };
}

export async function updateCustomer(id: string, body: Record<string, unknown>): Promise<{ customer: Customer }> {
  const raw = await apiFetch<{ customer: Record<string, unknown> }>(`/api/customers/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { customer: normalizeCustomer(raw.customer) };
}

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