import { timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getEnv } from "@/lib/env";
import { syncOrganizationLicenses } from "@/lib/site-agent/license-sync";

export async function POST(request: Request) {
  const expected = getEnv().LICENSE_SYNC_SECRET;
  const supplied = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
  const suppliedBytes = Buffer.from(supplied);
  const expectedBytes = Buffer.from(expected ?? "");
  if (!expected || suppliedBytes.length !== expectedBytes.length || !timingSafeEqual(suppliedBytes, expectedBytes)) {
    return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
  }
  const organizations = await db.site.findMany({ select: { organizationId: true }, distinct: ["organizationId"] });
  const results = await Promise.allSettled(organizations.map(({ organizationId }) => syncOrganizationLicenses(organizationId)));
  return NextResponse.json({ organizations: organizations.length, failed: results.filter((result) => result.status === "rejected").length, sitesFailed: results.reduce((count, result) => count + (result.status === "fulfilled" ? result.value.failed : 0), 0) });
}
