/**
 * Quotation Expiry Cron
 * Schedule: 0 21 * * * UTC (midnight Qatar)
 * Expires SENT/VIEWED quotations past their validUntil date
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
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)
    if (getDataSource("quotations") === "convex") {
      try {
        const { convexQuery, convexMutation } =
          await import("@/lib/convex-client");

        // Get all SENT/VIEWED quotations to check validUntil
        const allQuotations = await convexQuery(
          "quotations/queries:getQuotations",
          {
            userId: "__system__",
            status: "SENT",
            limit: 500,
          },
        );

        const now = Date.now();
        let expired = 0;

        if (allQuotations && Array.isArray(allQuotations)) {
          for (const q of allQuotations) {
            const quotation = q as {
              _id: string;
              validUntil?: number;
              status: string;
            };
            if (
              quotation.validUntil &&
              quotation.validUntil < now &&
              (quotation.status === "SENT" || quotation.status === "VIEWED")
            ) {
              await convexMutation("quotations/mutations:updateQuotation", {
                id: quotation._id as any,
                status: "EXPIRED",
              });
              expired++;
            }
          }
        }

        const duration = Date.now() - startTime;
        logger.info("Quotation expiry cron completed via Convex", {
          expired,
          durationMs: duration,
        });

        return NextResponse.json({
          success: true,
          durationMs: duration,
          expired,
        });
      } catch {
        // Fall through to Prisma
      }
    }

    const now = new Date();

    const result = await prisma.quotations.updateMany({
      where: {
        status: { in: ["SENT", "VIEWED"] },
        validUntil: { lt: now },
      },
      data: {
        status: "EXPIRED",
        updatedAt: now,
      },
    });

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

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