/**
 * POST /api/eterra/no-geom-scan
 *
 * Scans eTerra immovable list for a UAT and counts how many parcels
 * exist in the eTerra database but have no geometry in the remote
 * ArcGIS GIS layer (TERENURI_ACTIVE). Cross-references remotely.
 *
 * Body: { siruta: string }
 * Returns: { totalImmovables, withGeometry, noGeomCount, samples }
 *
 * Requires active eTerra session.
 */

import { NextResponse } from "next/server";
import { EterraClient } from "@/modules/parcel-sync/services/eterra-client";
import { getSessionCredentials } from "@/modules/parcel-sync/services/session-store";
import { scanNoGeometryParcels } from "@/modules/parcel-sync/services/no-geom-sync";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  try {
    const body = (await req.json()) as {
      siruta?: string;
      workspacePk?: number;
    };
    const siruta = String(body.siruta ?? "").trim();
    if (!/^\d+$/.test(siruta)) {
      return NextResponse.json(
        { error: "SIRUTA must be numeric" },
        { status: 400 },
      );
    }

    const session = getSessionCredentials();
    const username = String(
      session?.username || process.env.ETERRA_USERNAME || "",
    ).trim();
    const password = String(
      session?.password || process.env.ETERRA_PASSWORD || "",
    ).trim();
    if (!username || !password) {
      return NextResponse.json(
        { error: "Nu ești conectat la eTerra" },
        { status: 401 },
      );
    }

    const client = await EterraClient.create(username, password);

    // Global timeout: 2 minutes max for the entire scan
    const scanPromise = scanNoGeometryParcels(client, siruta, {
      workspacePk: body.workspacePk ?? null,
    });
    const timeoutPromise = new Promise<never>((_, reject) =>
      setTimeout(
        () =>
          reject(
            new Error(
              "Scanare timeout — serverul eTerra răspunde lent. Reîncearcă mai târziu.",
            ),
          ),
        120_000,
      ),
    );
    const result = await Promise.race([scanPromise, timeoutPromise]);

    return NextResponse.json(result);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
