/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * The shared "store catalogue" — the products the **admin** has selected from the
 * global catalogue (each with a quantity). This curated list is what **store
 * users** see and pick from. It's the design-stage bridge between the admin
 * catalogue page (InventoryView) and the user catalogue page (StoreCatalogView).
 *
 * Persisted in localStorage so the flow is fully demonstrable on one device; it
 * syncs live across tabs/pages via a storage event. The backend equivalents
 * (once built) are:
 *   • admin curates → POST /products/createproductlocation  (productid, qty, …)
 *   • user reads    → GET  /products/getlocationproducts
 * Swap `read`/`write` for those calls when the API is ready; the hook API stays.
 */

import { useFiestaProductLocations, useFiestaCreateProductLocation, useFiestaDeleteProductLocation } from './fiestaQueries';
import { FIESTA_TENANT_ID, FIESTA_PRIMARY_LOCATION_ID } from './fiestaApi';

export interface StoreCatalogueItem {
  productid: string;
  name: string;
  image: string;
  category: string;
  sku?: string;
  price: number;
  unit: string;
  /** Quantity the admin intends to stock for this product. */
  qty: number;
  status: string;
}

/**
 * Live view of the store catalogue + curation helpers. Re-renders whenever the
 * catalogue changes via React Query invalidation.
 */
export function useStoreCatalogue() {
  const q = useFiestaProductLocations({
    tenantid: FIESTA_TENANT_ID,
    locationid: FIESTA_PRIMARY_LOCATION_ID,
    pagesize: 500,
  });

  const items: StoreCatalogueItem[] = (q.data || []).filter((r: any) => r.status !== 'Inactive').map((r: any) => ({
    productid: String(r.productid),
    name: String(r.name || r.productname || ''),
    image: String(r.image || r.productimage || ''),
    category: String(r.category || r.categoryname || 'General'),
    sku: String(r.sku || ''),
    price: Number(r.price || 0),
    unit: String(r.unit || ''),
    qty: Number(r.quantity ?? r.qty ?? 0),
    status: String(r.status || 'Draft').charAt(0).toUpperCase() + String(r.status || 'Draft').slice(1).toLowerCase(),
  }));

  const mutation = useFiestaCreateProductLocation();
  const deleteMutation = useFiestaDeleteProductLocation();

  const has = (id: string) => items.some((i) => i.productid === id);
  const getQty = (id: string) => items.find((i) => i.productid === id)?.qty ?? 0;
  
  const add = (item: StoreCatalogueItem) => {
    mutation.mutate({
      tenantid: FIESTA_TENANT_ID,
      locationid: FIESTA_PRIMARY_LOCATION_ID,
      productid: Number(item.productid),
      qty: item.qty,
      price: item.price,
      status: item.status || 'Active'
    });
  };
  
  const remove = (id: string) => {
    const item = items.find(i => i.productid === id);
    if (!item) return;
    deleteMutation.mutate({
      tenantid: FIESTA_TENANT_ID,
      locationid: FIESTA_PRIMARY_LOCATION_ID,
      productid: Number(id)
    });
  };
  
  const setQty = (id: string, qty: number) => {
    const item = items.find(i => i.productid === id);
    if (!item) return;
    const safeQty = Math.max(1, Math.round(qty) || 1);
    mutation.mutate({
      tenantid: FIESTA_TENANT_ID,
      locationid: FIESTA_PRIMARY_LOCATION_ID,
      productid: Number(id),
      qty: safeQty,
      price: item.price,
      status: item.status || 'Active'
    });
  };
  
  const setPrice = (id: string, price: number) => {
    const item = items.find(i => i.productid === id);
    if (!item) return;
    mutation.mutate({
      tenantid: FIESTA_TENANT_ID,
      locationid: FIESTA_PRIMARY_LOCATION_ID,
      productid: Number(id),
      qty: item.qty || 0,
      price: price,
      status: 'Active' // Setting a price activates it
    });
  };

  return { items, has, getQty, add, remove, setQty, setPrice, isLoading: q.isLoading };
}
