import { sql } from "@/lib/db"; import { requireAuth } from "@/lib/jwt"; import { ACTIVE_STATUS_ARRAY, expireStaleRequests } from "@/lib/ride-lifecycle"; // GET — "does this rider have unfinished business?", answered in one call. // // active : a ride still in flight (requested/accepted/arrived/en_route). // Killing the app used to strand a rider away from their // tracking screen with no way back; the home banner reads // this to put them back on it. // pending_rating : a ride that finished recently and hasn't been rated yet, // so the prompt survives the app being backgrounded at // drop-off — the moment ratings are most often lost. export async function GET(req: Request) { const auth = requireAuth(req); if ("error" in auth) return auth.error; try { // Sweep searches that have run past the TTL (unscoped — this is one of the // lazy paths that stands in for a background worker), so the banner never // advertises a ride that is really long dead. await expireStaleRequests(); const active = await sql<{ ride_id: number; status: string; service: string; origin_address: string; destination_address: string; fare_price: number; driver_name: string | null; }>` SELECT r.ride_id, r.status, r.service, r.origin_address, r.destination_address, r.fare_price, NULLIF(TRIM(COALESCE(d.first_name, '') || ' ' || COALESCE(d.last_name, '')), '') AS driver_name FROM rides r LEFT JOIN drivers d ON d.id = r.driver_id WHERE r.user_id = ${auth.userId} AND r.status = ANY(${ACTIVE_STATUS_ARRAY}::text[]) ORDER BY r.created_at DESC LIMIT 1 `; // Only prompt for rides that ended in the last day — a week-old ride is a // nag, not a reminder. const pending = await sql<{ ride_id: number; destination_address: string; driver_name: string | null; driver_avatar: string | null; }>` SELECT r.ride_id, r.destination_address, NULLIF(TRIM(COALESCE(d.first_name, '') || ' ' || COALESCE(d.last_name, '')), '') AS driver_name, d.profile_image_url AS driver_avatar FROM rides r LEFT JOIN drivers d ON d.id = r.driver_id WHERE r.user_id = ${auth.userId} AND r.status = 'completed' AND r.completed_at > CURRENT_TIMESTAMP - INTERVAL '1 day' AND NOT EXISTS ( SELECT 1 FROM ride_ratings rr WHERE rr.ride_id = r.ride_id AND rr.rater_type = 'rider' ) ORDER BY r.completed_at DESC LIMIT 1 `; return Response.json({ data: { active: active[0] ?? null, pending_rating: pending[0] ?? null, }, }); } catch (error) { console.error("[RIDE_ACTIVE]: ", error); return Response.json({ error: "Internal Server Error" }, { status: 500 }); } }