/**
 * Verify Booking Payment API
 * GET /api/bookings/[id]/verify-payment
 *
 * Verifies if a Stripe checkout session was completed and updates the booking.
 * This is a fallback for when webhooks don't fire (development, webhook delays, etc.)
 */

import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";

export const dynamic = "force-dynamic";

interface RouteParams {
  params: Promise<{ id: string }>;
}

export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const { id: bookingId } = await params;
    const sessionId = request.nextUrl.searchParams.get("session_id");

    if (!bookingId) {
      return NextResponse.json(
        { success: false, error: "Booking ID required" },
        { status: 400 },
      );
    }

    // Get the booking
    const booking = await prisma.bookings.findUnique({
      where: { id: bookingId },
    });

    if (!booking) {
      return NextResponse.json(
        { success: false, error: "Booking not found" },
        { status: 404 },
      );
    }

    // If already marked as paid, return success
    if (booking.depositPaid) {
      logger.info("Booking already marked as paid", { bookingId });
      return NextResponse.json({
        success: true,
        alreadyPaid: true,
        booking: {
          id: booking.id,
          depositPaid: booking.depositPaid,
          status: booking.status,
        },
      });
    }

    // If no session ID provided, try to find a recent completed checkout session for this booking
    let checkoutSession = null;

    if (sessionId) {
      // Verify the specific session
      try {
        checkoutSession = await stripe.checkout.sessions.retrieve(sessionId);
      } catch (stripeError) {
        logger.warn("Failed to retrieve Stripe session", {
          sessionId,
          error: stripeError,
        });
      }
    }

    // If no session found, search for checkout sessions with this booking ID in metadata
    if (!checkoutSession) {
      try {
        const sessions = await stripe.checkout.sessions.list({
          limit: 10,
          expand: ["data.payment_intent"],
        });

        // Find a completed session for this booking
        checkoutSession =
          sessions.data.find(
            (s) =>
              s.metadata?.booking_id === bookingId &&
              s.payment_status === "paid",
          ) || null;
      } catch (listError) {
        logger.warn("Failed to list Stripe sessions", { error: listError });
      }
    }

    // Check if we found a paid session
    if (checkoutSession && checkoutSession.payment_status === "paid") {
      logger.info("Found paid checkout session, updating booking", {
        bookingId,
        sessionId: checkoutSession.id,
      });

      // Update booking as paid
      const updatedBooking = await prisma.bookings.update({
        where: { id: bookingId },
        data: {
          depositPaid: true,
          depositPaidAt: new Date(),
          depositPaymentId:
            (checkoutSession.payment_intent as string) || checkoutSession.id,
          status: "confirmed",
          updatedAt: new Date(),
        },
      });

      logger.info("Booking payment verified and updated", {
        bookingId,
        paymentIntent: checkoutSession.payment_intent,
      });

      return NextResponse.json({
        success: true,
        verified: true,
        booking: {
          id: updatedBooking.id,
          depositPaid: updatedBooking.depositPaid,
          status: updatedBooking.status,
        },
      });
    }

    // No paid session found
    return NextResponse.json({
      success: true,
      verified: false,
      message: "No completed payment found for this booking",
      booking: {
        id: booking.id,
        depositPaid: booking.depositPaid,
        status: booking.status,
      },
    });
  } catch (error) {
    logger.error("Payment verification error", {
      error: error instanceof Error ? error.message : "Unknown error",
    });

    return NextResponse.json(
      { success: false, error: "Failed to verify payment" },
      { status: 500 },
    );
  }
}
