const API = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000';

async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${API}${path}`, {
    ...init,
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...(init?.headers ?? {}),
    },
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ message: res.statusText }));
    throw Object.assign(new Error((err as { message?: string }).message ?? 'Request failed'), { status: res.status });
  }
  return res.json() as Promise<T>;
}

export const posApi = {
  /** Get current terminal info. Requires x-terminal-id header set by middleware. */
  me: () => apiFetch('/pos/terminals/me'),
  /** Bind terminal with code. */
  bind: (bindingCode: string) =>
    apiFetch('/pos/terminals/bind', { method: 'POST', body: JSON.stringify({ bindingCode }) }),
  /** Get POS config (store + terminal + payment methods + session status). */
  config: () => apiFetch('/pos/config'),
  /** List products by query. */
  searchProducts: (q: string, storeId?: string, limit = 20) =>
    apiFetch(`/pos/products/search?q=${encodeURIComponent(q)}&storeId=${storeId ?? ''}&limit=${limit}`),
  /** Get product by EAN. */
  productByEan: (ean: string) => apiFetch(`/pos/products/by-ean/${encodeURIComponent(ean)}`),
  /** Get product by SKU. */
  productBySku: (sku: string) => apiFetch(`/pos/products/by-sku/${encodeURIComponent(sku)}`),
};

export const authApi = {
  login: (email: string, password: string) =>
    apiFetch('/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) }),
  logout: () => apiFetch('/auth/logout', { method: 'POST' }),
};
