import { ref } from 'vue';
import { getTenders } from '../api/tenders.js';
import { AuctionItem } from '../models/AuctionItem.js';

export function useTenderSearch() {
  const searchText = ref('');
  const results = ref([]);
  const loading = ref(false);
  const error = ref('');
  const searched = ref(false);

  async function searchLicitatii() {
    loading.value = true;
    error.value = '';
    searched.value = true;
    results.value = [];

    try {
      // Add minimum loading time to show loading state
      const [data] = await Promise.all([
        getTenders(searchText.value),
        new Promise(resolve => setTimeout(resolve, 500)) // Minimum 500ms loading
      ]);

      let tendersArray = [];
      if (Array.isArray(data)) {
        tendersArray = data;
      } else if (Array.isArray(data.results)) {
        tendersArray = data.results;
      } else if (Array.isArray(data.items)) {
        tendersArray = data.items;
      } else {
        tendersArray = [];
      }

      // Convert raw API data to AuctionItem instances
      results.value = AuctionItem.fromApiDataArray(tendersArray);

      // Debug log to check what we got
      console.log('Search completed:', {
        searchText: searchText.value,
        totalResults: tendersArray.length,
        searched: searched.value
      });
    } catch (err) {
      error.value = err.message;
      console.error('Search error:', err);
    } finally {
      loading.value = false;
    }
  }

  return {
    searchText,
    results,
    loading,
    error,
    searched,
    searchLicitatii
  };
}
