import { MAP_MEASURE_LAYER_ID } from '../editable/measurement-tools/const'
import {
  MAP_LASSO_TOOLS_LAYER_ID,
  MAP_MASK_LAYER_ID,
} from '../editable/lasso-tools/const'
import type { Layer } from '../providers/layers/types'

const defaultLastLayerOrder = [
  MAP_MASK_LAYER_ID,
  MAP_LASSO_TOOLS_LAYER_ID,
  MAP_MEASURE_LAYER_ID,
]

/**
 * Sorts layers by their `order` property, placing internal tool layers (mask, lasso, measurement) at the end.
 *
 * @param layers - Array of layers to sort.
 * @returns A new sorted array of layers.
 */
export function sortLayers(layers: Layer[]) {
  const sortedLayers = layers
    .filter((layer) => !defaultLastLayerOrder.includes(layer.props.id!))
    .sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity))

  const lastLayers = defaultLastLayerOrder
    .map((id) => layers.find((layer) => layer.props.id === id))
    .filter((l) => !!l)

  return [...sortedLayers, ...lastLayers]
}
