import { NextResponse } from "next/server";
import { timingSafeEqual } from "crypto";
import { expireHolds } from "@/lib/orders";

/** Call every 10-15 minutes: curl -H "Authorization: Bearer $CRON_SECRET" https://yourdomain/api/cron/expire-holds
    Checkout also expires holds opportunistically, so a missed run never causes overselling. */
export async function POST(req: Request) { return handle(req); }
export async function GET(req: Request) { return handle(req); }
async function handle(req: Request) {
  const secret = process.env.CRON_SECRET ?? "";
  const given = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "");
  const a = Buffer.from(given), b = Buffer.from(secret);
  if (!secret || a.length !== b.length || !timingSafeEqual(a, b)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  return NextResponse.json({ released: await expireHolds() });
}
