/**
 * Quotation Recurring Cron
 * Schedule: 0 3 * * * UTC (6 AM Qatar)
 * Finds all due recurring templates and enqueues generation jobs
 */

import { NextResponse } from "next/server";
import { processDueRecurringTemplates } from "@/lib/services/quotation-recurring.service";
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, recurring template processing
    // reads templates from Convex. Full Convex routing requires
    // updating quotation-recurring.service.ts.
    if (getDataSource("quotations") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const quotations = await convexQuery(
          "quotations/queries:getQuotations",
          {
            userId: "__system__",
            limit: 100,
          },
        );
        if (quotations !== null) {
          logger.info("[Convex] Recurring templates check", {
            count: (quotations as unknown[]).length,
          });
        }
      } catch {
        // Fall through to Prisma-backed service
      }
    }

    const result = await processDueRecurringTemplates();

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

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