export interface Booking {
  id: string;
  restaurantId: string;
  branchId?: string;
  customerId?: string;
  guestName: string;
  guestPhone?: string;
  guestEmail?: string;
  partySize: number;
  date: string;
  time: string;
  tableNumber?: string;
  tableId?: string | null;
  startAt?: string | null;
  endAt?: string | null;
  durationMin?: number;
  bufferMin?: number;
  zone?: string;
  status: string;
  channel: string;
  notes?: string;
  specialRequests?: string;
  aiNotes?: string;
  aiConfidence?: number | null;
  occasion?: string;
  dietaryNeeds?: string[];
  isVip?: boolean;
  reminderSent?: boolean;
  confirmationChannel?: string;
  conversationId?: string;
  agentId?: string;
  createdAt: string;
  updatedAt: string;
}

export interface BookingListResponse {
  bookings: Booking[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

export function normalizeBooking(raw: Record<string, unknown>): Booking {
  return {
    id: String(raw.id ?? ''),
    restaurantId: String(raw.restaurant_id ?? raw.restaurantId ?? ''),
    branchId: raw.branch_id != null ? String(raw.branch_id) : (raw.branchId != null ? String(raw.branchId) : undefined),
    customerId: raw.customer_id != null ? String(raw.customer_id) : (raw.customerId != null ? String(raw.customerId) : undefined),
    guestName: String(raw.guest_name ?? raw.guestName ?? 'Guest'),
    guestPhone: raw.guest_phone != null ? String(raw.guest_phone) : (raw.guestPhone != null ? String(raw.guestPhone) : undefined),
    guestEmail: raw.guest_email != null ? String(raw.guest_email) : (raw.guestEmail != null ? String(raw.guestEmail) : undefined),
    partySize: Number(raw.party_size ?? raw.partySize ?? 1),
    date: String(raw.booking_date ?? raw.date ?? ''),
    time: String(raw.booking_time ?? raw.time ?? ''),
    tableNumber: raw.table_number != null ? String(raw.table_number) : (raw.tableNumber != null ? String(raw.tableNumber) : undefined),
    tableId: raw.table_id != null ? String(raw.table_id) : (raw.tableId != null ? String(raw.tableId) : null),
    startAt: raw.start_at != null ? String(raw.start_at) : (raw.startAt != null ? String(raw.startAt) : null),
    endAt: raw.end_at != null ? String(raw.end_at) : (raw.endAt != null ? String(raw.endAt) : null),
    durationMin: raw.duration_min != null ? Number(raw.duration_min) : (raw.durationMin != null ? Number(raw.durationMin) : 90),
    bufferMin: raw.buffer_min != null ? Number(raw.buffer_min) : (raw.bufferMin != null ? Number(raw.bufferMin) : 15),
    zone: raw.zone != null ? String(raw.zone) : undefined,
    status: String(raw.status ?? 'pending'),
    channel: String(raw.channel ?? 'chat'),
    notes: raw.notes != null ? String(raw.notes) : undefined,
    specialRequests: raw.special_requests != null ? String(raw.special_requests) : (raw.specialRequests != null ? String(raw.specialRequests) : undefined),
    aiNotes: raw.ai_notes != null ? String(raw.ai_notes) : (raw.aiNotes != null ? String(raw.aiNotes) : undefined),
    aiConfidence: raw.ai_confidence != null ? Number(raw.ai_confidence) : (raw.aiConfidence != null ? Number(raw.aiConfidence) : null),
    occasion: raw.occasion != null ? String(raw.occasion) : undefined,
    dietaryNeeds: Array.isArray(raw.dietary_needs) ? raw.dietary_needs.map(String) : (Array.isArray(raw.dietaryNeeds) ? raw.dietaryNeeds.map(String) : undefined),
    isVip: Boolean(raw.is_vip ?? raw.isVip ?? false),
    reminderSent: Boolean(raw.reminder_sent ?? raw.reminderSent ?? false),
    confirmationChannel: raw.confirmation_channel != null ? String(raw.confirmation_channel) : (raw.confirmationChannel != null ? String(raw.confirmationChannel) : undefined),
    conversationId: raw.conversation_id != null ? String(raw.conversation_id) : (raw.conversationId != null ? String(raw.conversationId) : undefined),
    agentId: raw.agent_id != null ? String(raw.agent_id) : (raw.agentId != null ? String(raw.agentId) : undefined),
    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 listBookings(params: Record<string, string> = {}): Promise<BookingListResponse> {
  const qs = new URLSearchParams(params).toString();
  const raw = await apiFetch<{ bookings: Record<string, unknown>[]; total: number; page: number; limit: number; pages: number }>(`/api/bookings${qs ? '?' + qs : ''}`);
  return {
    bookings: (raw.bookings ?? []).map(normalizeBooking),
    total: raw.total,
    page: raw.page,
    limit: raw.limit,
    pages: raw.pages,
  };
}

export async function getBooking(id: string): Promise<{ booking: Booking }> {
  const raw = await apiFetch<{ booking: Record<string, unknown> }>(`/api/bookings/${id}`);
  return { booking: normalizeBooking(raw.booking) };
}

export async function createBooking(body: Record<string, unknown>): Promise<{ booking: Booking }> {
  const raw = await apiFetch<{ booking: Record<string, unknown> }>('/api/bookings', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { booking: normalizeBooking(raw.booking) };
}

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

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