import prisma from "@/lib/db";
import { sendGuideCompletionReminderEmail, sendBookingCompletedEmail } from "@/lib/email";

/**
 * Auto-complete bookings that are 24 hours past their tour date
 * This function should be called by a cron job or scheduled task
 * 
 * Process:
 * 1. Find all CONFIRMED bookings where tour date was >= 24 hours ago
 * 2. Update status to COMPLETED
 * 3. Send completion email to explorer
 * 4. Send reminder email to guide (if not already sent)
 */
export async function autoCompleteBookings() {
  try {
    // Calculate the cutoff time (24 hours ago)
    const cutoffDate = new Date();
    cutoffDate.setHours(cutoffDate.getHours() - 24);

    // Find all confirmed bookings past the cutoff
    const bookingsToComplete = await prisma.booking.findMany({
      where: {
        status: "CONFIRMED",
        date: {
          lte: cutoffDate,
        },
      },
      include: {
        tour: {
          include: {
            createdBy: true,
          },
        },
        user: true,
      },
    });

    console.log(
      `Found ${bookingsToComplete.length} bookings to auto-complete`
    );

    const results = {
      completed: 0,
      failed: 0,
      errors: [] as string[],
    };

    // Process each booking
    for (const booking of bookingsToComplete) {
      try {
        // Update booking status
        await prisma.booking.update({
          where: { id: booking.id },
          data: { status: "COMPLETED" },
        });

        // Send completion email to explorer
        await sendBookingCompletedEmail({
          explorerName: booking.user.name || "Traveler",
          explorerEmail: booking.user.email,
          tourTitle: booking.tour.title,
          guideName: booking.tour.createdBy.name || "Guide",
          tourDate: booking.date.toLocaleDateString("en-US", {
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "numeric",
          }),
          tourSlug: booking.tour.slug,
        });

        console.log(`Auto-completed booking ${booking.id}`);
        results.completed++;
      } catch (error) {
        console.error(`Failed to auto-complete booking ${booking.id}:`, error);
        results.failed++;
        results.errors.push(`Booking ${booking.id}: ${error}`);
      }
    }

    return results;
  } catch (error) {
    console.error("Error in autoCompleteBookings:", error);
    throw error;
  }
}

/**
 * Send completion reminder emails to guides
 * This should be called 24 hours after tour date
 * Separate from auto-completion to give guides a chance to mark it themselves
 * 
 * Process:
 * 1. Find all CONFIRMED bookings where tour date was exactly 24 hours ago
 * 2. Send reminder email to guide to mark as completed
 */
export async function sendCompletionReminders() {
  try {
    // Calculate time range (23-25 hours ago to catch the 24-hour mark)
    const startTime = new Date();
    startTime.setHours(startTime.getHours() - 25);
    
    const endTime = new Date();
    endTime.setHours(endTime.getHours() - 23);

    // Find confirmed bookings in this time range
    const bookingsNeedingReminder = await prisma.booking.findMany({
      where: {
        status: "CONFIRMED",
        date: {
          gte: startTime,
          lte: endTime,
        },
      },
      include: {
        tour: {
          include: {
            createdBy: true,
          },
        },
        user: true,
      },
    });

    console.log(
      `Found ${bookingsNeedingReminder.length} bookings needing completion reminder`
    );

    const results = {
      sent: 0,
      failed: 0,
      errors: [] as string[],
    };

    for (const booking of bookingsNeedingReminder) {
      try {
        await sendGuideCompletionReminderEmail({
          guideName: booking.tour.createdBy.name || "Guide",
          guideEmail: booking.tour.createdBy.email,
          tourTitle: booking.tour.title,
          explorerName: booking.user.name || "Explorer",
          bookingDate: booking.date.toLocaleDateString("en-US", {
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "numeric",
          }),
          bookingId: booking.id,
        });

        console.log(`Sent completion reminder for booking ${booking.id}`);
        results.sent++;
      } catch (error) {
        console.error(`Failed to send reminder for booking ${booking.id}:`, error);
        results.failed++;
        results.errors.push(`Booking ${booking.id}: ${error}`);
      }
    }

    return results;
  } catch (error) {
    console.error("Error in sendCompletionReminders:", error);
    throw error;
  }
}

/**
 * Check if a booking can be reviewed
 * Returns true only if the booking status is COMPLETED
 */
export function canReviewBooking(bookingStatus: string): boolean {
  return bookingStatus === "COMPLETED";
}

/**
 * Check if a booking is ready for auto-completion
 * Returns true if booking is CONFIRMED and 24+ hours have passed since tour date
 */
export function isReadyForAutoCompletion(
  bookingStatus: string,
  tourDate: Date
): boolean {
  if (bookingStatus !== "CONFIRMED") {
    return false;
  }

  const now = new Date();
  const hoursSinceTour = (now.getTime() - tourDate.getTime()) / (1000 * 60 * 60);
  
  return hoursSinceTour >= 24;
}
