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

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

export const listingService = {
  async getListings(filters?: Partial<SearchFilters>): Promise<Listing[]> {
    const params = new URLSearchParams();
    if (filters?.query) params.set("q", filters.query);
    if (filters?.category) params.set("category", filters.category);
    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);
    const res = await fetch(`${BASE_URL}/api/marketplace/listings?${params}`);
    if (!res.ok) throw new Error("Failed to fetch listings");
    return res.json();
  },

  async getListing(slug: string): Promise<Listing> {
    const res = await fetch(`${BASE_URL}/api/marketplace/listings/${slug}`);
    if (!res.ok) throw new Error("Listing not found");
    return res.json();
  },

  async createListing(data: Partial<Listing>): Promise<Listing> {
    const res = await fetch(`${BASE_URL}/api/marketplace/listings`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    if (!res.ok) throw new Error("Failed to create listing");
    return res.json();
  },

  async updateListing(id: string, data: Partial<Listing>): Promise<Listing> {
    const res = await fetch(`${BASE_URL}/api/marketplace/listings/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    if (!res.ok) throw new Error("Failed to update listing");
    return res.json();
  },

  async deleteListing(id: string): Promise<void> {
    const res = await fetch(`${BASE_URL}/api/marketplace/listings/${id}`, {
      method: "DELETE",
    });
    if (!res.ok) throw new Error("Failed to delete listing");
  },

  async toggleWishlist(listingId: string): Promise<{ wishlisted: boolean }> {
    const res = await fetch(`${BASE_URL}/api/marketplace/wishlist/${listingId}`, {
      method: "POST",
    });
    if (!res.ok) throw new Error("Failed to toggle wishlist");
    return res.json();
  },

  async getWishlist(): Promise<Listing[]> {
    const res = await fetch(`${BASE_URL}/api/marketplace/wishlist`);
    if (!res.ok) throw new Error("Failed to fetch wishlist");
    return res.json();
  },
};
