/**
 * Eligible Bookings for Review Requests API
 * GET - List completed bookings that haven't had a review request sent yet
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

const log = logger.scope("EligibleBookingsAPI");

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const result = await convexQuery(
          "reviews/queries:getEligibleBookings",
          {
            userId: effectiveUserId,
            limit: 100,
          },
        );
        if (result !== null) {
          return NextResponse.json({ success: true, bookings: result });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    // Get IDs of bookings that already have a review request
    const existingRequests = await prisma.review_requests.findMany({
      where: { userId: effectiveUserId, bookingId: { not: null } },
      select: { bookingId: true },
    });
    const requestedBookingIds = new Set(
      existingRequests.map((r) => r.bookingId).filter(Boolean),
    );

    // Get completed bookings from the last 90 days
    const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
    const bookings = await prisma.bookings.findMany({
      where: {
        userId: effectiveUserId,
        status: "completed",
        appointmentDate: { gte: ninetyDaysAgo },
      },
      orderBy: { appointmentDate: "desc" },
      take: 100,
      select: {
        id: true,
        customerName: true,
        customerPhone: true,
        customerEmail: true,
        service: true,
        appointmentDate: true,
      },
    });

    // Filter out bookings that already have a review request
    const eligible = bookings
      .filter((b) => !requestedBookingIds.has(b.id))
      .map((b) => ({
        id: b.id,
        customerName: b.customerName,
        customerPhone: b.customerPhone,
        customerEmail: b.customerEmail,
        serviceName: b.service,
        completedAt: b.appointmentDate.toISOString(),
      }));

    return NextResponse.json({ success: true, bookings: eligible });
  } catch (error) {
    log.error("Failed to list eligible bookings", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
