/**
 * Review Reminders Cron Endpoint
 *
 * Scheduled job that:
 * 1. Sends follow-up reminders for unanswered review requests
 * 2. Expires stale review requests past their expiry date
 *
 * Security: Requires CRON_SECRET authorization header
 */

import { NextResponse } from "next/server";
import {
  processReviewReminders,
  expireStaleRequests,
} from "@/lib/services/review-reminder.service";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

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

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 reminders cron attempt");
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

  try {
    // Convex data-source routing (WU-18)
    // When reviews domain is on Convex, reminder/expiry reads
    // review requests from Convex. Full Convex routing requires
    // updating review-reminder.service.ts.
    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const requests = await convexQuery(
          "reviews/queries:getReviewRequests",
          {
            userId: "__system__",
            status: "SENT",
            limit: 500,
          },
        );
        if (requests !== null) {
          log.info("[Convex] Review requests for reminder/expiry processing", {
            count: (requests as unknown[]).length,
          });
        }
      } catch {
        // Fall through to Prisma-backed service
      }
    }

    const [reminderResult, expireResult] = await Promise.all([
      processReviewReminders(),
      expireStaleRequests(),
    ]);

    const duration = Date.now() - startTime;

    log.info("Review reminders cron completed", {
      duration,
      reminders: reminderResult,
      expired: expireResult,
    });

    return NextResponse.json({
      success: true,
      duration: `${duration}ms`,
      reminders: reminderResult,
      expired: expireResult,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Unknown error";
    log.error("Review reminders 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";
