/**
 * UAT geometry fetcher — retrieves the boundary polygon for a SIRUTA
 * from the LIMITE_UAT layer. Used as spatial filter for dynamic layers.
 */

import type { EsriGeometry } from "./eterra-client";
import { EterraClient } from "./eterra-client";
import { findLayerById } from "./eterra-layers";

const findAdminField = (fields: string[]) => {
  const preferred = [
    "ADMIN_UNIT_ID",
    "SIRUTA",
    "UAT_ID",
    "SIRUTA_UAT",
    "UAT_SIRUTA",
  ];
  const upper = fields.map((f) => f.toUpperCase());
  for (const key of preferred) {
    const idx = upper.indexOf(key);
    if (idx >= 0) return fields[idx];
  }
  return null;
};

export const fetchUatGeometry = async (
  client: EterraClient,
  siruta: string,
): Promise<EsriGeometry> => {
  const layer = findLayerById("LIMITE_UAT");
  if (!layer) throw new Error("LIMITE_UAT not configured");

  const fields = await client.getLayerFieldNames(layer);
  const adminField = findAdminField(fields);
  if (!adminField) throw new Error("LIMITE_UAT missing admin field");

  const where = `${adminField}=${siruta}`;
  const features = await client.fetchAllLayerByWhere(layer, where, {
    outFields: adminField,
    returnGeometry: true,
    pageSize: 1,
  });

  const geometry = features[0]?.geometry as EsriGeometry | undefined;
  if (!geometry?.rings?.length) throw new Error("UAT geometry not found");
  return geometry;
};
