// src/stores/search.ts

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { customerService } from '../services/customerService'

// Define a type for what a search result looks like.
interface CustomerSearchResult {
  id: number;
  customer_first_name: string;
  customer_last_name: string;
  customer_address: string;
  customer_town: string;
  customer_state: number; // Changed to number to match your database
  // You can add other properties here if needed
}

export const useSearchStore = defineStore('search', () => {
  // --- STATE ---
  const searchTerm = ref('');
  const searchResults = ref<CustomerSearchResult[]>([]);
  const isLoading = ref(false);
  let debounceTimer: any = null;

  // --- GETTERS ---
  const showResults = computed(() => {
    // FIX: The box should be visible as long as the user has typed enough.
    // The component inside will handle showing the "No results found" message.
    return searchTerm.value.length > 1;
  });

  // --- ACTIONS ---
  async function fetchSearchResults() {
    if (searchTerm.value.length < 2) {
      searchResults.value = [];
      return;
    }

    isLoading.value = true;
    try {
      const response = await customerService.search(searchTerm.value);
      searchResults.value = (response.data?.customers || []) as CustomerSearchResult[];
    } catch { // No `error` parameter as requested
      searchResults.value = [];
    } finally {
      isLoading.value = false;
    }
  }

  function debouncedSearch() {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      fetchSearchResults();
    }, 400);
  }

  function clearSearch() {
    searchTerm.value = '';
    searchResults.value = [];
    clearTimeout(debounceTimer);
  }

  // --- RETURN ---
  return {
    searchTerm,
    searchResults,
    isLoading,
    showResults,
    debouncedSearch,
    clearSearch,
  }
})
