// Faza C.2 — hard-disable legacy writes to architools_postgres Gis* tables
// when the api.gis.ac path is enabled for the caller (per-user pilot or global).
//
// Called at the top of every route handler that triggers a write through
// `prisma.gisFeature.*`, `prisma.gisUat.*`, `prisma.gisSyncRun.*`,
// `prisma.gisSyncRule.*` — directly or via parcel-sync services. Read-only
// handlers (sync-status, export-local, *_GET) are intentionally NOT gated:
// freezing reads breaks rollback ergonomics with no benefit, since Faza H
// only needs writes to stop.
//
// Returns a NextResponse(410) when the legacy path is blocked. Returns null
// when the caller may continue. Background/cron callers (no session) hit the
// `USE_GIS_AC === "1"` fast-path; user-initiated requests fall to the
// pilot-list check.

import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/core/auth/auth-options";
import { useGisAcFlag } from "./use-gis-ac";

export async function gateLegacyGisWrite(
  endpoint: string,
): Promise<NextResponse | null> {
  if (process.env.USE_GIS_AC === "1") {
    return NextResponse.json(
      {
        error: "deprecated",
        endpoint,
        message:
          "Local GisFeature writes are disabled. Use the api.gis.ac equivalent.",
      },
      { status: 410 },
    );
  }
  const session = await getServerSession(authOptions).catch(() => null);
  if (useGisAcFlag(session?.user?.email)) {
    return NextResponse.json(
      {
        error: "deprecated",
        endpoint,
        message:
          "This user is on the api.gis.ac path; refresh the UI to use the new flow.",
      },
      { status: 410 },
    );
  }
  return null;
}
