import { NextResponse } from "next/server";
import { autoCompleteBookings, sendCompletionReminders } from "@/lib/booking-completion";

/**
 * GET /api/cron/complete-bookings
 * Vercel Cron Job to auto-complete bookings and send reminder emails
 * 
 * This endpoint is called hourly by Vercel's cron job scheduler.
 * Only works in production deployments.
 * 
 * Workflow:
 * 1. Send reminder emails to guides for bookings 24h past tour date
 * 2. Auto-complete bookings that are still CONFIRMED after 24h
 * 
 * Configuration: vercel.json
 */
export async function GET() {
  try {
    console.log("Starting booking completion cron job...");

    // Step 1: Send completion reminders to guides
    const reminderResults = await sendCompletionReminders();
    console.log("Completion reminders sent:", reminderResults);

    // Step 2: Auto-complete bookings that are 24+ hours past tour date
    const completionResults = await autoCompleteBookings();
    console.log("Bookings auto-completed:", completionResults);

    return NextResponse.json({
      success: true,
      timestamp: new Date().toISOString(),
      reminderResults,
      completionResults,
    });
  } catch (error) {
    console.error("Error in booking completion cron job:", error);
    return NextResponse.json(
      {
        error: "Failed to complete bookings",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}
