import type { MapGeoJSONFeature } from "maplibre-gl";
import type { DetailFeature } from "../types";
import { formatValue } from "../utils/format-value";
import { SOURCE_LAYERS, type WaterNetworkSourceId } from "./sources";

export function getFeatureId(feature: MapGeoJSONFeature) {
  const raw = feature.properties?.id ?? feature.id;
  return raw === undefined || raw === null ? "" : String(raw);
}

export function getWaterNetworkSourceId(feature: MapGeoJSONFeature): WaterNetworkSourceId | null {
  for (const [sourceId, sourceLayer] of Object.entries(SOURCE_LAYERS) as [WaterNetworkSourceId, string][]) {
    if (feature.source === sourceId || feature.sourceLayer === sourceLayer) {
      return sourceId;
    }
  }

  return null;
}

export function toDetailFeature(feature: MapGeoJSONFeature): DetailFeature {
  const sourceId = getWaterNetworkSourceId(feature) ?? "junctions";
  const id = getFeatureId(feature);
  const labels = getFeatureLabels(sourceId, id, feature.properties ?? {});

  return {
    id,
    layer: sourceId,
    title: labels.title,
    subtitle: labels.subtitle,
    properties: feature.properties ?? {}
  };
}

function getFeatureLabels(sourceId: WaterNetworkSourceId, id: string, properties: Record<string, unknown>) {
  if (sourceId === "pipes") {
    return {
      title: `管线 ${id || "未命名"}`,
      subtitle: `DN${formatValue(properties.diameter)} · ${formatValue(properties.length)} m`
    };
  }

  if (sourceId === "valves") {
    return {
      title: `阀门 ${id || "未命名"}`,
      subtitle: `DN${formatValue(properties.diameter)} · ${formatValue(properties.v_type)}`
    };
  }

  if (sourceId === "reservoirs") {
    return {
      title: `水库 ${id || "未命名"}`,
      subtitle: `水头 ${formatValue(properties.head)} · 模式 ${formatValue(properties.pattern)}`
    };
  }

  if (sourceId === "scada") {
    return {
      title: `SCADA ${id || "未命名"}`,
      subtitle: `${formatValue(properties.type)} · 关联 ${formatValue(properties.associated_element_id)}`
    };
  }

  return {
    title: `节点 ${id || "未命名"}`,
    subtitle: `需水量 ${formatValue(properties.demand)} · 高程 ${formatValue(properties.elevation)} m`
  };
}
