import { serverSupabaseServiceRole } from '#supabase/server' export default defineEventHandler(async (event) => { const body = await readBody(event) const poll = body._poll !== false delete body._poll const supabase = serverSupabaseServiceRole(event) const paramsHash = computeSearchHash(body) // Buscar en cache (TTL 1 hora) const { data: cached } = await supabase .from('search_cache') .select('trips, cheapest_price, total_results, fetched_at') .eq('params_hash', paramsHash) .gte('fetched_at', new Date(Date.now() - 60 * 60 * 1000).toISOString()) .single() if (cached) { const trips = (cached.trips as any[]) || [] return { trips, notComplete: false, contractVersion: 0, responseId: `cache-${paramsHash.slice(0, 8)}` } } // Sin cache — llamar a Flightics const result = poll ? await searchTripsComplete(body, 3) : await searchTrips(body) // Guardar en cache (upsert por params_hash) if (result.trips && result.trips.length > 0) { const prices = result.trips.map(t => t.totalCost).filter(p => p > 0) const cheapest = prices.length > 0 ? Math.min(...prices) : null await supabase .from('search_cache') .upsert({ params_hash: paramsHash, search_params: body, trips: result.trips, cheapest_price: cheapest, total_results: result.trips.length, fetched_at: new Date().toISOString() }, { onConflict: 'params_hash' }) } return result })