export interface Branch {
  id: string;
  restaurantId: string;
  name: string;
  address?: string;
  phone?: string;
  email?: string;
  isActive: boolean;
  timezone?: string;
  createdAt: string;
  updatedAt: string;
}

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

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

export async function switchBranch(branchId: string): Promise<{ ok: boolean }> {
  return apiFetch<{ ok: boolean }>('/api/auth/switch-branch', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ branchId }),
  });
}
