/**
 * Custom hook for fetching schools with SWR
 */

'use client';

import useSWR from 'swr';
import { fetcher } from '@/lib/api';
import type { SchoolsResponse, SchoolSearchParams } from '@/lib/types';

export function useSchools(params: SchoolSearchParams = {}, shouldFetch: boolean = true) {
  const queryParams = new URLSearchParams();

  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== '') {
      queryParams.set(key, String(value));
    }
  });

  const queryString = queryParams.toString();
  const url = `/schools${queryString ? `?${queryString}` : ''}`;

  const { data, error, isLoading, mutate } = useSWR<SchoolsResponse>(
    shouldFetch ? url : null,
    fetcher,
    {
      revalidateOnFocus: false,
      dedupingInterval: 5000, // 5 seconds
    }
  );

  return {
    schools: data?.schools || [],
    pagination: data ? {
      page: data.page,
      page_size: data.page_size,
      total: data.total,
      total_pages: data.total_pages,
    } : null,
    searchMode: data?.search_mode,
    locationInfo: data?.location_info,
    isLoading,
    error,
    mutate,
  };
}
