import { HONGYUAN_BOUNDS, WMS_IMAGE_SIZE } from "@/config/layers"
import { requestJson } from "./request"

const GEOSERVER_WMS_URL = import.meta.env.VITE_GEOSERVER_WMS_URL || "/geoserver/ne/wms"
const GEOSERVER_WFS_URL = import.meta.env.VITE_GEOSERVER_WFS_URL || GEOSERVER_WMS_URL.replace(/\/wms$/i, "/wfs")

function appendParams(url, params) {
  const search = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== "") {
      search.append(key, value)
    }
  })
  return `${url}${url.includes("?") ? "&" : "?"}${search.toString()}`
}

export function buildWmsGetMapUrl(layer, options = {}) {
  const bounds = options.bounds || HONGYUAN_BOUNDS
  const size = options.size || WMS_IMAGE_SIZE
  return appendParams(options.url || GEOSERVER_WMS_URL, {
    service: "WMS",
    version: "1.1.1",
    request: "GetMap",
    layers: layer.layerName,
    styles: layer.styles || "",
    format: "image/png",
    transparent: true,
    tiled: true,
    srs: "EPSG:4326",
    bbox: [bounds.west, bounds.south, bounds.east, bounds.north].join(","),
    width: size.width,
    height: size.height,
    CQL_FILTER: options.cqlFilter || layer.cqlFilter,
    _: Date.now(),
  })
}

export function buildFeatureInfoUrl(layer, point, options = {}) {
  const bounds = options.bounds || HONGYUAN_BOUNDS
  const size = options.size || WMS_IMAGE_SIZE
  return appendParams(options.url || GEOSERVER_WMS_URL, {
    service: "WMS",
    version: "1.1.1",
    request: "GetFeatureInfo",
    layers: layer.layerName,
    query_layers: layer.layerName,
    styles: layer.styles || "",
    info_format: "application/json",
    feature_count: 5,
    srs: "EPSG:4326",
    bbox: [bounds.west, bounds.south, bounds.east, bounds.north].join(","),
    width: size.width,
    height: size.height,
    x: Math.round(point.x),
    y: Math.round(point.y),
    buffer: options.buffer ?? layer.queryBuffer ?? 8,
    CQL_FILTER: options.cqlFilter || layer.cqlFilter,
  })
}

export async function getFeatureInfo(layer, point, options = {}) {
  const url = buildFeatureInfoUrl(layer, point, options)
  return requestJson(url, {
    credentials: "include",
  })
}

export function buildWfsGetFeatureUrl(layerName, options = {}) {
  return appendParams(options.url || GEOSERVER_WFS_URL, {
    service: "WFS",
    version: options.version || "1.0.0",
    request: "GetFeature",
    typeName: layerName,
    outputFormat: "json",
    propertyName: Array.isArray(options.propertyName) ? options.propertyName.join(",") : options.propertyName,
    CQL_FILTER: options.cqlFilter,
    maxFeatures: options.maxFeatures || 200000,
  })
}

export async function getWfsFeatureProperties(layerName, options = {}) {
  const url = buildWfsGetFeatureUrl(layerName, options)
  return requestJson(url, {
    credentials: "include",
    timeout: options.timeout || 20000,
  })
}

export function normalizeFeatureInfo(response) {
  const feature = response?.features?.[0]
  if (!feature) return null
  const properties = feature.properties || {}
  return {
    id: feature.id || properties.gid || properties.objectid || properties.OBJECTID,
    properties,
    feature,
  }
}
