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

/**
 * TanStack Query hooks that wrap the raw API functions in `./api`.
 *
 * Components call these hooks (never `fetch`/the api functions directly) so they
 * get caching, dedup, loading/error state, and refetching for free. Covers the
 * non-mobile `/api/rest/*` catalog from developer.nearledaily.com.
 */

import { useQuery } from '@tanstack/react-query';
import {
  DEFAULT_TENANT_ID,
  DEFAULT_CONFIG_ID,
  getDashboardKpis,
  // Users
  getUsers,
  getAppRoles,
  // Orders
  getOrders,
  getOrderSummary,
  // Tenants
  getTenantInfo,
  getTenantLocations,
  getCustomersByTenant,
  getTenantCustomers,
  getTenantDeliveries,
  // Products
  getProductCategories,
  getSubcategory,
  getProductSubcategories,
  getProductVariants,
  getStockStatement,
  getProductsCount,
  // Apps & Locations
  getAppLocations,
  getAppLocationConfig,
  getAppTypes,
  // Partners
  getPartners,
  getRiderShifts,
  // Invoice
  getInvoiceInsight,
} from './api';

/** Centralized, stable query keys — keep all cache keys discoverable in one place. */
export const queryKeys = {
  dashboardKpis: (tenantid: number) => ['dashboardKpis', tenantid] as const,
  // Users
  users: (params: Record<string, unknown>) => ['users', params] as const,
  appRoles: (configid: number) => ['appRoles', configid] as const,
  // Orders
  orders: (params: Record<string, unknown>) => ['orders', params] as const,
  orderSummary: (tenantid: number, fromdate: string, todate: string, configid: number) =>
    ['orderSummary', tenantid, fromdate, todate, configid] as const,
  // Tenants
  tenantInfo: (tenantid: number) => ['tenantInfo', tenantid] as const,
  tenantLocations: (tenantid: number) => ['tenantLocations', tenantid] as const,
  customersByTenant: (params: Record<string, unknown>) => ['customersByTenant', params] as const,
  tenantCustomers: (params: Record<string, unknown>) => ['tenantCustomers', params] as const,
  tenantDeliveries: (params: Record<string, unknown>) => ['tenantDeliveries', params] as const,
  // Products
  productCategories: (moduleid: number) => ['productCategories', moduleid] as const,
  subcategory: (moduleid: number, categoryid: number) => ['subcategory', moduleid, categoryid] as const,
  productSubcategories: (categoryid: number) => ['productSubcategories', categoryid] as const,
  productVariants: (tenantid: number, subcategoryid: number) =>
    ['productVariants', tenantid, subcategoryid] as const,
  stockStatement: (params: Record<string, unknown>) => ['stockStatement', params] as const,
  productsCount: (params: Record<string, unknown>) => ['productsCount', params] as const,
  // Apps & Locations
  appLocations: () => ['appLocations'] as const,
  appLocationConfig: () => ['appLocationConfig'] as const,
  appTypes: (tag: string) => ['appTypes', tag] as const,
  // Partners
  partners: (params: Record<string, unknown>) => ['partners', params] as const,
  riderShifts: (applocationid: number) => ['riderShifts', applocationid] as const,
  // Invoice
  invoiceInsight: (tenantid: number) => ['invoiceInsight', tenantid] as const,
};

// ── Dashboard ─────────────────────────────────────────────────────────────────
export function useDashboardKpis(tenantid: number = DEFAULT_TENANT_ID) {
  return useQuery({
    queryKey: queryKeys.dashboardKpis(tenantid),
    queryFn: () => getDashboardKpis(tenantid),
  });
}

// ── Users ───────────────────────────────────────────────────────────────────
export function useUsers(opts: { tenantid: number; roleid?: number; limit?: number; offset?: number }) {
  return useQuery({
    queryKey: queryKeys.users(opts),
    queryFn: () => getUsers(opts),
    enabled: Boolean(opts.tenantid),
  });
}

export function useAppRoles(configid = 15) {
  return useQuery({ queryKey: queryKeys.appRoles(configid), queryFn: () => getAppRoles(configid) });
}

// ── Orders ────────────────────────────────────────────────────────────────────
export function useOrders(opts: {
  start: string;
  end: string;
  status: string;
  limit?: number;
  offset?: number;
}) {
  return useQuery({
    queryKey: queryKeys.orders(opts),
    queryFn: () => getOrders(opts),
    enabled: Boolean(opts.start && opts.end && opts.status),
  });
}

export function useOrderSummary(
  tenantid: number,
  fromdate: string,
  todate: string,
  configid: number = DEFAULT_CONFIG_ID,
) {
  return useQuery({
    queryKey: queryKeys.orderSummary(tenantid, fromdate, todate, configid),
    queryFn: () => getOrderSummary(tenantid, fromdate, todate, configid),
    enabled: Boolean(tenantid && fromdate && todate),
  });
}

// ── Tenants ───────────────────────────────────────────────────────────────────
export function useTenantInfo(tenantid: number = DEFAULT_TENANT_ID) {
  return useQuery({ queryKey: queryKeys.tenantInfo(tenantid), queryFn: () => getTenantInfo(tenantid) });
}

export function useTenantLocations(tenantid: number = DEFAULT_TENANT_ID) {
  return useQuery({
    queryKey: queryKeys.tenantLocations(tenantid),
    queryFn: () => getTenantLocations(tenantid),
  });
}

export function useCustomersByTenant(opts: { tenantid: number; limit?: number; offset?: number }) {
  return useQuery({
    queryKey: queryKeys.customersByTenant(opts),
    queryFn: () => getCustomersByTenant(opts),
    enabled: Boolean(opts.tenantid),
  });
}

export function useTenantCustomers(opts: {
  tenantid: number;
  locationid: number;
  limit?: number;
  offset?: number;
}) {
  return useQuery({
    queryKey: queryKeys.tenantCustomers(opts),
    queryFn: () => getTenantCustomers(opts),
    enabled: Boolean(opts.tenantid && opts.locationid),
  });
}

export function useTenantDeliveries(opts: {
  tenantid: number;
  status?: string;
  fromdate: string;
  todate: string;
  keyword?: string;
  limit?: number;
  offset?: number;
}) {
  return useQuery({
    queryKey: queryKeys.tenantDeliveries(opts),
    queryFn: () => getTenantDeliveries(opts),
    enabled: Boolean(opts.tenantid && opts.fromdate && opts.todate),
  });
}

// ── Products ──────────────────────────────────────────────────────────────────
export function useProductCategories(moduleid: number) {
  return useQuery({
    queryKey: queryKeys.productCategories(moduleid),
    queryFn: () => getProductCategories(moduleid),
    enabled: Boolean(moduleid),
  });
}

export function useSubcategory(moduleid: number, categoryid: number) {
  return useQuery({
    queryKey: queryKeys.subcategory(moduleid, categoryid),
    queryFn: () => getSubcategory(moduleid, categoryid),
    enabled: Boolean(moduleid && categoryid),
  });
}

export function useProductSubcategories(categoryid: number) {
  return useQuery({
    queryKey: queryKeys.productSubcategories(categoryid),
    queryFn: () => getProductSubcategories(categoryid),
    enabled: Boolean(categoryid),
  });
}

export function useProductVariants(tenantid: number, subcategoryid: number) {
  return useQuery({
    queryKey: queryKeys.productVariants(tenantid, subcategoryid),
    queryFn: () => getProductVariants(tenantid, subcategoryid),
    enabled: Boolean(tenantid && subcategoryid),
  });
}

export function useStockStatement(opts: {
  tenantid: number;
  locationid: number;
  subcategoryid?: number;
  keyword?: string;
  limit?: number;
  offset?: number;
}) {
  return useQuery({
    queryKey: queryKeys.stockStatement(opts),
    queryFn: () => getStockStatement(opts),
    enabled: Boolean(opts.tenantid && opts.locationid),
  });
}

export function useProductsCount(opts: { tenantid: number; categoryid: number; subcategoryid?: number }) {
  return useQuery({
    queryKey: queryKeys.productsCount(opts),
    queryFn: () => getProductsCount(opts),
    enabled: Boolean(opts.tenantid && opts.categoryid),
  });
}

// ── Apps & Locations ──────────────────────────────────────────────────────────
export function useAppLocations() {
  return useQuery({ queryKey: queryKeys.appLocations(), queryFn: () => getAppLocations() });
}

export function useAppLocationConfig() {
  return useQuery({ queryKey: queryKeys.appLocationConfig(), queryFn: () => getAppLocationConfig() });
}

export function useAppTypes(tag: string) {
  return useQuery({
    queryKey: queryKeys.appTypes(tag),
    queryFn: () => getAppTypes(tag),
    enabled: Boolean(tag),
  });
}

// ── Partners ──────────────────────────────────────────────────────────────────
export function usePartners(opts: {
  applocationid: number;
  partnerid?: number;
  limit?: number;
  offset?: number;
}) {
  return useQuery({
    queryKey: queryKeys.partners(opts),
    queryFn: () => getPartners(opts),
    enabled: Boolean(opts.applocationid),
  });
}

export function useRiderShifts(applocationid: number) {
  return useQuery({
    queryKey: queryKeys.riderShifts(applocationid),
    queryFn: () => getRiderShifts(applocationid),
    enabled: Boolean(applocationid),
  });
}

// ── Invoice ───────────────────────────────────────────────────────────────────
export function useInvoiceInsight(tenantid: number = DEFAULT_TENANT_ID) {
  return useQuery({
    queryKey: queryKeys.invoiceInsight(tenantid),
    queryFn: () => getInvoiceInsight(tenantid),
  });
}
