/**
 * GET /api/geoportal/feature?objectId=...&siruta=...&sourceLayer=...
 *
 * Returns a single GIS feature with enrichment data for the info panel.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/core/storage/prisma";

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

export async function GET(req: Request) {
  try {
    const url = new URL(req.url);
    const objectId = url.searchParams.get("objectId");
    const siruta = url.searchParams.get("siruta");
    const sourceLayer = url.searchParams.get("sourceLayer") ?? "";

    if (!objectId || !siruta) {
      return NextResponse.json(
        { error: "Parametri lipsa: objectId si siruta sunt obligatorii" },
        { status: 400 }
      );
    }

    // UAT features come from GisUat table
    if (sourceLayer === "gis_uats") {
      const uat = await prisma.gisUat.findUnique({
        where: { siruta },
        select: {
          siruta: true,
          name: true,
          county: true,
          areaValue: true,
          workspacePk: true,
        },
      });

      if (!uat) {
        return NextResponse.json({ error: "UAT negasit" }, { status: 404 });
      }

      return NextResponse.json({
        feature: {
          id: uat.siruta,
          layerId: "LIMITE_UAT",
          siruta: uat.siruta,
          objectId: 0,
          cadastralRef: null,
          areaValue: uat.areaValue,
          enrichment: null,
          enrichedAt: null,
          extra: {
            name: uat.name,
            county: uat.county,
            workspacePk: uat.workspacePk,
          },
        },
      });
    }

    // GisFeature (parcels, buildings)
    const objId = parseInt(objectId, 10);
    if (isNaN(objId)) {
      return NextResponse.json({ error: "objectId invalid" }, { status: 400 });
    }

    const feature = await prisma.gisFeature.findFirst({
      where: {
        objectId: objId,
        siruta,
      },
      select: {
        id: true,
        layerId: true,
        siruta: true,
        objectId: true,
        cadastralRef: true,
        areaValue: true,
        enrichment: true,
        enrichedAt: true,
        inspireId: true,
      },
    });

    if (!feature) {
      return NextResponse.json(
        { error: "Feature negasit in baza de date" },
        { status: 404 }
      );
    }

    return NextResponse.json({
      feature: {
        id: feature.id,
        layerId: feature.layerId,
        siruta: feature.siruta,
        objectId: feature.objectId,
        cadastralRef: feature.cadastralRef,
        areaValue: feature.areaValue,
        enrichment: feature.enrichment as Record<string, unknown> | null,
        enrichedAt: feature.enrichedAt?.toISOString() ?? null,
      },
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
