import type { Feature, FeatureCollection, Geometry } from "geojson";

export const VALUE_LABEL_SOURCE_ID = "workbench-value-label";
export const VALUE_LABEL_LAYER_IDS = ["workbench-value-label-point", "workbench-value-label-line"] as const;

export function getNumericFeatureProperties(properties: Record<string, unknown> | null | undefined) {
  return Object.entries(properties ?? {})
    .filter((entry): entry is [string, number] => typeof entry[1] === "number" && Number.isFinite(entry[1]))
    .sort(([a], [b]) => a.localeCompare(b));
}

export function formatFeatureValue(value: number, precision: number, unit = "") {
  const safePrecision = Math.min(3, Math.max(0, Math.trunc(precision)));
  const safeUnit = unit.trim().slice(0, 16);
  return `${value.toFixed(safePrecision)}${safeUnit ? ` ${safeUnit}` : ""}`;
}

export function createValueLabelCollection(
  feature: Feature,
  property: string,
  precision: number,
  unit = ""
): FeatureCollection {
  const value = feature.properties?.[property];
  if (typeof value !== "number" || !Number.isFinite(value)) {
    throw new Error("INVALID_VALUE_PROPERTY");
  }

  return {
    type: "FeatureCollection",
    features: [{
      type: "Feature",
      geometry: feature.geometry as Geometry,
      properties: { label: formatFeatureValue(value, precision, unit) }
    }]
  };
}

export function createEmptyValueLabelCollection(): FeatureCollection {
  return { type: "FeatureCollection", features: [] };
}
