/**
 * Quotation Penalties Cron
 * Schedule: 0 22 * * * UTC (1 AM Qatar)
 * Applies late-payment penalties to overdue quotations
 */

import { NextResponse } from "next/server";
import { processOverduePenalties } from "@/lib/services/quotation-penalties.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, penalty processing reads
    // overdue quotations from Convex. Full Convex routing requires
    // updating quotation-penalties.service.ts to accept a data source param.
    if (getDataSource("quotations") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        // Pre-fetch overdue quotations from Convex for logging
        const quotations = await convexQuery(
          "quotations/queries:getQuotations",
          {
            userId: "__system__",
            status: "OVERDUE",
            limit: 500,
          },
        );
        if (quotations !== null) {
          logger.info("[Convex] Overdue quotations for penalty processing", {
            count: (quotations as unknown[]).length,
          });
        }
      } catch {
        // Fall through to Prisma-backed service
      }
    }

    const result = await processOverduePenalties();

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

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