/**
 * Quotation Reminders Cron
 * Schedule: 0 6 * * * UTC (9 AM Qatar)
 * Processes due quotation payment reminders
 */

import { NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

export const dynamic = "force-dynamic";
export const maxDuration = 60;

function isAuthorized(request: Request): boolean {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) return false;
  const authHeader = request.headers.get("authorization");
  return authHeader === `Bearer ${cronSecret}`;
}

export async function GET(request: Request) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const startTime = Date.now();

  try {
    // Convex data-source routing (WU-18)
    // When quotations domain is on Convex, payment reminder processing
    // reads quotations from Convex. Full Convex routing requires
    // updating quotation-reminders.service.ts.
    if (getDataSource("quotations") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const quotations = await convexQuery(
          "quotations/queries:getQuotations",
          {
            userId: "__system__",
            limit: 500,
          },
        );
        if (quotations !== null) {
          logger.info("[Convex] Quotations for reminder processing", {
            count: (quotations as unknown[]).length,
          });
        }
      } catch {
        // Fall through to Prisma-backed service
      }
    }

    // Dynamic import to prevent build-time page data collection failure
    const { processDueReminders } =
      await import("@/lib/services/quotation-reminders.service");
    const result = await processDueReminders();

    const duration = Date.now() - startTime;
    logger.info("Quotation reminders cron completed", {
      ...result,
      durationMs: duration,
    });

    return NextResponse.json({
      success: true,
      durationMs: duration,
      ...result,
    });
  } catch (error) {
    logger.error("Quotation reminders cron failed", error);
    return NextResponse.json(
      {
        success: false,
        error: "Internal error",
        durationMs: Date.now() - startTime,
      },
      { status: 500 },
    );
  }
}
