export interface Branch {
  id: string;
  restaurantId: string;
  name: string;
  address?: string;
  phone?: string;
  email?: string;
  isActive: boolean;
  timezone?: string;
  createdAt: string;
  updatedAt: string;
  // Storefront fields (snake_case to match server payload, used by storefront UI)
  slug?: string;
  storefront_enabled?: boolean;
  accepts_dine_in?: boolean;
  accepts_takeaway?: boolean;
  accepts_delivery?: boolean;
  min_order_value?: number;
  storefront_message?: string | null;
  qr_style_json?: Record<string, unknown>;
  // Operating hours loaded from the database for the edit form.
  hours?: Record<string, unknown>;
  // Per-branch quiet hours window (Task #238). Local hour 0-23.
  quiet_hours_enabled?: boolean;
  quiet_hours_start?: number;
  quiet_hours_end?: number;
  /**
   * WhatsApp per-WABA send rate cap (msgs/sec). Used by the campaign dispatcher
   * to stay within the branch's Meta WABA tier limit. Default: 10.
   */
  whatsapp_send_rate?: number;
  // True when the user has manually set a custom branch name; auto-rename on
  // restaurant rename will not touch this branch.
  name_customized?: boolean;
}

export interface BranchListResponse {
  branches: Branch[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

function normalizeBranch(raw: Record<string, unknown>): Branch {
  return {
    id: String(raw.id ?? ''),
    restaurantId: String(raw.restaurant_id ?? raw.restaurantId ?? ''),
    name: String(raw.name ?? ''),
    address: raw.address != null ? String(raw.address) : undefined,
    phone: raw.phone != null ? String(raw.phone) : undefined,
    email: raw.email != null ? String(raw.email) : undefined,
    isActive: Boolean(raw.is_active ?? raw.isActive ?? true),
    timezone: raw.timezone != null ? String(raw.timezone) : undefined,
    createdAt: String(raw.created_at ?? raw.createdAt ?? ''),
    updatedAt: String(raw.updated_at ?? raw.updatedAt ?? ''),
    // Pass-through storefront fields (snake_case preserved for storefront UI)
    slug: raw.slug != null ? String(raw.slug) : undefined,
    storefront_enabled: raw.storefront_enabled != null ? Boolean(raw.storefront_enabled) : undefined,
    accepts_dine_in: raw.accepts_dine_in != null ? Boolean(raw.accepts_dine_in) : undefined,
    accepts_takeaway: raw.accepts_takeaway != null ? Boolean(raw.accepts_takeaway) : undefined,
    accepts_delivery: raw.accepts_delivery != null ? Boolean(raw.accepts_delivery) : undefined,
    min_order_value: raw.min_order_value != null ? Number(raw.min_order_value) : undefined,
    storefront_message: raw.storefront_message != null ? String(raw.storefront_message) : null,
    qr_style_json: (raw.qr_style_json as Record<string, unknown> | undefined) ?? undefined,
    hours: raw.hours != null ? (raw.hours as Record<string, unknown>) : undefined,
    quiet_hours_enabled: raw.quiet_hours_enabled != null ? Boolean(raw.quiet_hours_enabled) : undefined,
    quiet_hours_start:   raw.quiet_hours_start   != null ? Number(raw.quiet_hours_start)   : undefined,
    quiet_hours_end:     raw.quiet_hours_end     != null ? Number(raw.quiet_hours_end)     : undefined,
    whatsapp_send_rate:  raw.whatsapp_send_rate  != null ? Number(raw.whatsapp_send_rate)  : undefined,
    name_customized:     raw.name_customized     != null ? Boolean(raw.name_customized)    : undefined,
  };
}

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

export async function getBranch(id: string): Promise<{ branch: Branch }> {
  const raw = await apiFetch<{ branch: Record<string, unknown> }>(`/api/branches/${id}`);
  return { branch: normalizeBranch(raw.branch) };
}

export async function createBranch(body: Record<string, unknown>): Promise<{ branch: Branch }> {
  const raw = await apiFetch<{ branch: Record<string, unknown> }>('/api/branches', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { branch: normalizeBranch(raw.branch) };
}

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

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

// Pass `null` to switch the session into the restaurant-wide
// "All branches" view. Server enforces that only owners may do this.
export async function switchBranch(branchId: string | null): Promise<{ ok: boolean }> {
  return apiFetch<{ ok: boolean }>('/api/auth/switch-branch', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ branchId }),
  });
}
