import { NextResponse } from "next/server" import { fetchQuery } from "convex/nextjs" import { api } from "@/convex/_generated/api" import { hasConvexUrl } from "@/lib/convex-config" import { rankListingsForQuery, type CachedEbayListing, type EbayCacheState, } from "@/lib/ebay-parts-match" import { searchStaticEbayListings } from "@/lib/server/manual-parts-data" function getCacheStateFallback(message?: string): EbayCacheState { return { key: "manual-parts", status: "success", lastSuccessfulAt: Date.now(), lastAttemptAt: null, nextEligibleAt: null, lastError: null, consecutiveFailures: 0, queryCount: 0, itemCount: 0, sourceQueries: [], freshnessMs: 0, isStale: true, listingCount: 0, activeListingCount: 0, message: message || "Using bundled manual cache.", } } export async function GET(request: Request) { const { searchParams } = new URL(request.url) const keywords = searchParams.get("keywords")?.trim() || "" const maxResults = Math.min( Math.max(Number.parseInt(searchParams.get("maxResults") || "6", 10) || 6, 1), 20 ) if (!keywords) { return NextResponse.json( { error: "Keywords parameter is required" }, { status: 400 } ) } if (!hasConvexUrl()) { const staticResults = await searchStaticEbayListings(keywords, maxResults) return NextResponse.json({ query: keywords, results: staticResults, cache: getCacheStateFallback(), }) } try { const [overview, listings] = await Promise.all([ fetchQuery(api.ebay.getCacheOverview, {}), fetchQuery(api.ebay.listCachedListings, { limit: 200 }), ]) const ranked = rankListingsForQuery( keywords, listings as CachedEbayListing[], maxResults ) return NextResponse.json({ query: keywords, results: ranked, cache: overview, }) } catch (error) { console.error("Failed to load cached eBay listings:", error) const staticResults = await searchStaticEbayListings(keywords, maxResults) return NextResponse.json( { query: keywords, results: staticResults, cache: getCacheStateFallback( error instanceof Error ? `Using bundled manual cache because cached listings failed: ${error.message}` : "Using bundled manual cache because cached listings failed." ), }, { status: 200 } ) } }