/**
 * Review Auto-Send Cron Endpoint
 *
 * Scheduled job that sends review requests to customers ~24 hours
 * after a completed booking.
 *
 * Security: Requires CRON_SECRET authorization header
 */

import { NextResponse } from "next/server";
import { processAutoReviewRequests } from "@/lib/services/review-auto-trigger.service";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

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

async function isAuthorized(request: Request): Promise<boolean> {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) return false;

  const authHeader = request.headers.get("authorization");
  if (!authHeader) return false;

  return authHeader === `Bearer ${cronSecret}`;
}

export async function GET(request: Request) {
  if (!(await isAuthorized(request))) {
    log.warn("Unauthorized review auto-send cron attempt");
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  log.info("Starting review auto-send cron job");
  const startTime = Date.now();

  try {
    // Convex data-source routing (WU-18)
    // When reviews domain is on Convex, auto-send reads eligible
    // bookings and creates review requests in Convex.
    // Full Convex routing requires updating review-auto-trigger.service.ts.
    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        // Check for eligible bookings that need review requests
        const eligibleBookings = await convexQuery(
          "reviews/queries:getEligibleBookings",
          {
            userId: "__system__",
            limit: 100,
          },
        );
        if (eligibleBookings !== null) {
          log.info("[Convex] Eligible bookings for review auto-send", {
            count: (eligibleBookings as unknown[]).length,
          });
        }
      } catch {
        // Fall through to Prisma-backed service
      }
    }

    const result = await processAutoReviewRequests();
    const duration = Date.now() - startTime;

    log.info("Review auto-send cron completed", { duration, ...result });

    return NextResponse.json({
      success: true,
      duration: `${duration}ms`,
      ...result,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Unknown error";
    log.error("Review auto-send cron failed", { error: msg });

    return NextResponse.json(
      {
        success: false,
        error: msg,
        duration: `${Date.now() - startTime}ms`,
      },
      { status: 500 },
    );
  }
}

export async function POST(request: Request) {
  return GET(request);
}

export const dynamic = "force-dynamic";
