import type { Listing, SearchFilters } from "@/types/marketplace";
import { ITEMS_PER_PAGE } from "@/constants/marketplace";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export interface SearchResult {
  listings: Listing[];
  total: number;
  page: number;
  totalPages: number;
  suggestions?: string[];
}

export const searchService = {
  async search(
    filters: Partial<SearchFilters>,
    page = 1
  ): Promise<SearchResult> {
    const params = new URLSearchParams({ page: String(page), limit: String(ITEMS_PER_PAGE) });
    if (filters.query) params.set("q", filters.query);
    if (filters.category) params.set("category", filters.category);
    if (filters.subcategory) params.set("subcategory", filters.subcategory);
    if (filters.minPrice) params.set("minPrice", String(filters.minPrice));
    if (filters.maxPrice) params.set("maxPrice", String(filters.maxPrice));
    if (filters.sortBy) params.set("sortBy", filters.sortBy);
    if (filters.location) params.set("location", filters.location);
    if (filters.deliveryType) params.set("deliveryType", filters.deliveryType);
    filters.condition?.forEach((c) => params.append("condition", c));

    const res = await fetch(`${BASE_URL}/api/marketplace/search?${params}`);
    if (!res.ok) throw new Error("Search failed");
    return res.json();
  },

  async getSuggestions(query: string): Promise<string[]> {
    if (!query.trim()) return [];
    const res = await fetch(
      `${BASE_URL}/api/marketplace/search/suggestions?q=${encodeURIComponent(query)}`
    );
    if (!res.ok) return [];
    return res.json();
  },

  async getTrending(): Promise<string[]> {
    const res = await fetch(`${BASE_URL}/api/marketplace/search/trending`);
    if (!res.ok) return [];
    return res.json();
  },

  async getRecentSearches(): Promise<string[]> {
    if (typeof window === "undefined") return [];
    try {
      return JSON.parse(localStorage.getItem("marketplace_recent_searches") ?? "[]");
    } catch {
      return [];
    }
  },

  saveSearch(query: string): void {
    if (typeof window === "undefined" || !query.trim()) return;
    try {
      const existing: string[] = JSON.parse(
        localStorage.getItem("marketplace_recent_searches") ?? "[]"
      );
      const updated = [query, ...existing.filter((q) => q !== query)].slice(0, 8);
      localStorage.setItem("marketplace_recent_searches", JSON.stringify(updated));
    } catch {
      // ignore
    }
  },

  clearRecentSearches(): void {
    if (typeof window === "undefined") return;
    localStorage.removeItem("marketplace_recent_searches");
  },
};
