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;
  marketingOptOut?: boolean;
  optOutAt?: string;
  optOutReason?: string;
  lastCampaignId?: string;
  loyalty?: {
    balance: number;
    lifetimePoints: number;
    tierName?: string;
    tierColor?: string;
  } | null;
}

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

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 ?? ''),
    marketingOptOut: raw.marketing_opt_out === true || raw.marketingOptOut === true,
    optOutAt: raw.opt_out_at != null ? String(raw.opt_out_at) : undefined,
    optOutReason: raw.opt_out_reason != null ? String(raw.opt_out_reason) : undefined,
    lastCampaignId: raw.last_campaign_id != null ? String(raw.last_campaign_id) : (raw.lastCampaignId != null ? String(raw.lastCampaignId) : undefined),
    loyalty: raw.loyalty_balance != null
      ? {
          balance: Number(raw.loyalty_balance ?? 0),
          lifetimePoints: Number(raw.loyalty_lifetime_points ?? 0),
          tierName: raw.loyalty_tier_name != null ? String(raw.loyalty_tier_name) : undefined,
          tierColor: raw.loyalty_tier_color != null ? String(raw.loyalty_tier_color) : undefined,
        }
      : null,
  };
}

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; loyalty_enabled?: boolean }>(`/api/customers${qs ? '?' + qs : ''}`);
  return {
    customers: (raw.customers ?? []).map(normalizeCustomer),
    total: raw.total,
    page: raw.page,
    limit: raw.limit,
    pages: raw.pages,
    loyaltyEnabled: raw.loyalty_enabled === true,
  };
}

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' });
}
