/**
 * POST /api/geoportal/enrich
 *
 * Per-parcel enrichment — calls the proven /api/eterra/search internally
 * and saves the result to GisFeature.enrichment.
 *
 * Body: { featureId: string } or { siruta: string, objectId: number }
 */
import { NextResponse } from "next/server";
import { prisma } from "@/core/storage/prisma";
import { headers } from "next/headers";

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

export async function POST(req: Request) {
  try {
    const body = (await req.json()) as { featureId?: string; siruta?: string; objectId?: number };

    // Find feature
    let feature;
    if (body.featureId) {
      feature = await prisma.gisFeature.findUnique({
        where: { id: body.featureId },
        select: { id: true, objectId: true, siruta: true, cadastralRef: true, areaValue: true },
      });
    } else if (body.siruta && body.objectId) {
      feature = await prisma.gisFeature.findFirst({
        where: { siruta: body.siruta, objectId: body.objectId },
        select: { id: true, objectId: true, siruta: true, cadastralRef: true, areaValue: true },
      });
    }

    if (!feature) {
      return NextResponse.json({ error: "Parcela negasita in DB" }, { status: 404 });
    }

    const cadRef = feature.cadastralRef ?? "";
    if (!cadRef) {
      return NextResponse.json({ error: "Parcela fara numar cadastral" }, { status: 400 });
    }

    // Call the proven /api/eterra/search endpoint internally
    const headersList = await headers();
    const cookie = headersList.get("cookie") ?? "";
    const origin = req.headers.get("origin") ?? headersList.get("host") ?? "localhost:3000";
    const protocol = origin.includes("localhost") ? "http" : "https";
    const baseUrl = origin.startsWith("http") ? origin : `${protocol}://${origin}`;

    const searchResp = await fetch(`${baseUrl}/api/eterra/search`, {
      method: "POST",
      headers: { "Content-Type": "application/json", cookie },
      body: JSON.stringify({ siruta: feature.siruta, search: cadRef }),
    });

    if (!searchResp.ok) {
      const err = await searchResp.json().catch(() => ({}));
      return NextResponse.json(
        { error: (err as Record<string, string>).error ?? `eTerra search esuat (${searchResp.status})` },
        { status: searchResp.status }
      );
    }

    const searchData = await searchResp.json() as {
      results: Array<{
        nrCad: string; nrCF: string; nrCFVechi: string; nrTopo: string;
        intravilan: string; categorieFolosinta: string; adresa: string;
        proprietari: string; proprietariActuali: string; proprietariVechi: string;
        suprafata: number | null; solicitant: string; immovablePk: string;
      }>;
    };

    const match = searchData.results?.[0];
    if (!match) {
      return NextResponse.json({ error: "Parcela negasita in registrul eTerra" }, { status: 404 });
    }

    // Building cross-ref: check CLADIRI_ACTIVE in local DB for this parcel
    let hasBuilding = 0;
    let buildLegal = 0;
    const baseCad = cadRef.includes("-") ? cadRef.split("-")[0]! : cadRef;
    if (baseCad) {
      const cladiri = await prisma.gisFeature.findMany({
        where: {
          layerId: "CLADIRI_ACTIVE",
          siruta: feature.siruta,
          OR: [
            { cadastralRef: { startsWith: baseCad + "-" } },
            { cadastralRef: baseCad },
          ],
        },
        select: { attributes: true },
      });
      for (const c of cladiri) {
        const attrs = c.attributes as Record<string, unknown>;
        hasBuilding = 1;
        if (
          Number(attrs.IS_LEGAL ?? 0) === 1 ||
          String(attrs.IS_LEGAL ?? "").toLowerCase() === "true"
        ) {
          buildLegal = 1;
        }
      }
    }

    // Convert to enrichment format (same as enrichFeatures uses)
    const enrichment = {
      NR_CAD: match.nrCad || cadRef,
      NR_CF: match.nrCF || "",
      NR_CF_VECHI: match.nrCFVechi || "",
      NR_TOPO: match.nrTopo || "",
      ADRESA: match.adresa || "",
      PROPRIETARI: match.proprietariActuali || match.proprietari || "",
      PROPRIETARI_VECHI: match.proprietariVechi || "",
      SUPRAFATA_2D: match.suprafata ?? feature.areaValue ?? "",
      SUPRAFATA_R: match.suprafata ? Math.round(match.suprafata) : (feature.areaValue ? Math.round(feature.areaValue) : ""),
      SOLICITANT: match.solicitant || "",
      INTRAVILAN: match.intravilan || "",
      CATEGORIE_FOLOSINTA: match.categorieFolosinta || "",
      HAS_BUILDING: hasBuilding,
      BUILD_LEGAL: buildLegal,
    };

    // Persist
    await prisma.gisFeature.update({
      where: { id: feature.id },
      data: { enrichment: enrichment as object, enrichedAt: new Date() },
    });

    return NextResponse.json({ status: "ok", message: "Parcela imbogatita cu succes", enrichment });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
