import { NextRequest } from "next/server";
import { getAllTrips, getTripById, getTripsByStatus, getTripsByRegion } from "@/lib/trips";

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");
    const status = searchParams.get("status");
    const region = searchParams.get("region");
    
    // Get specific trip by ID
    if (id) {
      const trip = getTripById(id);
      if (!trip) {
        return new Response(JSON.stringify({ error: "Trip not found" }), {
          status: 404,
          headers: { "content-type": "application/json" }
        });
      }
      return new Response(JSON.stringify({ trip }), {
        headers: { "content-type": "application/json" }
      });
    }
    
    // Filter by status
    if (status) {
      const trips = getTripsByStatus(status as any);
      return new Response(JSON.stringify({ trips, count: trips.length }), {
        headers: { "content-type": "application/json" }
      });
    }
    
    // Filter by region
    if (region) {
      const trips = getTripsByRegion(region);
      return new Response(JSON.stringify({ trips, count: trips.length }), {
        headers: { "content-type": "application/json" }
      });
    }
    
    // Get all trips
    const trips = getAllTrips();
    return new Response(JSON.stringify({ 
      trips,
      count: trips.length,
      byStatus: {
        planning: getTripsByStatus("planning").length,
        booked: getTripsByStatus("booked").length,
        completed: getTripsByStatus("completed").length
      }
    }), {
      headers: { "content-type": "application/json" }
    });
    
  } catch (e: any) {
    return new Response(JSON.stringify({ 
      error: e?.message || "Failed to retrieve trips" 
    }), { 
      status: 500, 
      headers: { "content-type": "application/json" } 
    });
  }
}
