import { NextRequest, NextResponse } from "next/server"; import { getAvailability, getEffectiveMinStay } from "@/src/lib/beds24"; import { calculatePrice } from "@/src/lib/pricing"; import { getApartmentBySlug, bookingConfig } from "@/src/config/apartments"; import { nightsBetween, addDays } from "@/src/lib/date"; export const dynamic = "force-dynamic"; export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url); const apartmentSlug = searchParams.get("apartmentSlug"); const start = searchParams.get("start"); const end = searchParams.get("end"); if (!apartmentSlug || !start || !end) { return NextResponse.json( { error: "Missing required parameters: apartmentSlug, start, end" }, { status: 400 } ); } const apartment = getApartmentBySlug(apartmentSlug); if (!apartment) { return NextResponse.json( { error: "Apartment not found" }, { status: 404 } ); } const nights = nightsBetween(start, end); if (nights <= 0) { return NextResponse.json( { error: "End date must be after start date" }, { status: 400 } ); } const minStayNights = await getEffectiveMinStay( apartment.houseId, apartment.beds24PropertyId, apartment.beds24RoomId, start, bookingConfig.minStayNights ); const minStayValid = nights >= minStayNights; const availability = await getAvailability({ houseId: apartment.houseId, propertyId: apartment.beds24PropertyId, roomId: apartment.beds24RoomId, start, end, }); // Fetch Beds24's own short-stay rate for the same arrival date, purely to // display a genuine "savings vs. short-term rate" figure — this never // changes the actual price charged (see calculatePrice()). let referenceNightlyRate: number | undefined; if (availability.available && nights > bookingConfig.referenceStayNights) { try { const reference = await getAvailability({ houseId: apartment.houseId, propertyId: apartment.beds24PropertyId, roomId: apartment.beds24RoomId, start, end: addDays(start, bookingConfig.referenceStayNights), }); if (reference.available) { referenceNightlyRate = reference.price; } } catch (referenceError) { console.error("Reference price lookup failed:", referenceError); } } const price = calculatePrice( availability.price, nights, availability.currency, referenceNightlyRate ); return NextResponse.json({ apartmentSlug, start, end, nights, available: availability.available, minStayValid, minStayNights, maxGuests: apartment.maxGuests, price, }); } catch (error) { console.error("Availability API error:", error); return NextResponse.json( { error: "Failed to fetch availability" }, { status: 500 } ); } }