"use client";

import { useQuery } from '@tanstack/react-query';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';

// ---------------------------------------------------------------------------
// Main hook — fetches all static data in a single request
// ---------------------------------------------------------------------------

export function useLookups() {
  const { lookups } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('lookups', 'static-data'),
    queryFn: () => lookups.getStaticData(),
    staleTime: Infinity, // ETag-based; never auto-refetch
  });
}

// ---------------------------------------------------------------------------
// Convenience hooks for individual lookup arrays
// ---------------------------------------------------------------------------

export function useTaskCategories() {
  const { data, ...rest } = useLookups();
  const arr = data?.task_categories;
  return { data: Array.isArray(arr) ? arr : [], ...rest };
}

export function useTaskPriorities() {
  const { data, ...rest } = useLookups();
  const arr = data?.task_priorities;
  return { data: Array.isArray(arr) ? arr : [], ...rest };
}

export function useTaskFrequencies() {
  const { data, ...rest } = useLookups();
  const arr = data?.task_frequencies;
  return { data: Array.isArray(arr) ? arr : [], ...rest };
}

export function useContractorSpecialties() {
  const { data, ...rest } = useLookups();
  const arr = data?.contractor_specialties;
  return { data: Array.isArray(arr) ? arr : [], ...rest };
}

export function useResidenceTypes() {
  const { data, ...rest } = useLookups();
  const arr = data?.residence_types;
  return { data: Array.isArray(arr) ? arr : [], ...rest };
}

// ---------------------------------------------------------------------------
// O(1) lookup helpers — find a single item by ID from cached data
// ---------------------------------------------------------------------------

export function useTaskCategory(id: number | null | undefined) {
  const { data: categories } = useTaskCategories();
  if (!id) return null;
  return categories.find((c) => c.id === id) ?? null;
}

export function useTaskPriority(id: number | null | undefined) {
  const { data: priorities } = useTaskPriorities();
  if (!id) return null;
  return priorities.find((p) => p.id === id) ?? null;
}

export function useTaskFrequency(id: number | null | undefined) {
  const { data: frequencies } = useTaskFrequencies();
  if (!id) return null;
  return frequencies.find((f) => f.id === id) ?? null;
}

export function useContractorSpecialty(id: number | null | undefined) {
  const { data: specialties } = useContractorSpecialties();
  if (!id) return null;
  return specialties.find((s) => s.id === id) ?? null;
}
