import { describe, it, expect } from 'vitest'
import { getAllValues, getMaskValues, repairSelfIntersection } from './util'
import type { LassoToolsData } from './types'

const polygon = {
  type: 'Polygon' as const,
  coordinates: [
    [
      [0, 0],
      [1, 0],
      [1, 1],
      [0, 1],
      [0, 0],
    ],
  ],
}

const maskValue: LassoToolsData = {
  id: 'mask-1',
  type: 'mask',
  geometry: polygon,
  properties: { label: 'Mask 1', visible: true },
}

const drawValue: LassoToolsData = {
  id: 'draw-1',
  type: 'draw',
  geometry: polygon,
  properties: { label: 'Drawing 1', visible: true },
}

const values = { 'mask-1': maskValue, 'draw-1': drawValue }

describe('lasso-tools util', () => {
  it('getMaskValues returns only mask geometries', () => {
    const result = getMaskValues({ values })
    expect(result.map((v) => v.id)).toEqual(['mask-1'])
  })

  it('getAllValues returns mask + draw geometries', () => {
    const result = getAllValues({ values })
    expect(result.map((v) => v.id).sort()).toEqual(['draw-1', 'mask-1'])
  })

  it('both helpers tolerate undefined values', () => {
    expect(getMaskValues({})).toEqual([])
    expect(getAllValues({})).toEqual([])
  })
})

describe('repairSelfIntersection', () => {
  it('leaves a simple polygon unchanged', () => {
    const result = repairSelfIntersection(polygon)
    expect(result).toEqual({ geometry: polygon, repaired: false })
  })

  it('leaves non-polygon geometries unchanged', () => {
    const line = {
      type: 'LineString' as const,
      coordinates: [
        [0, 0],
        [1, 1],
      ],
    }
    const result = repairSelfIntersection(line)
    expect(result).toEqual({ geometry: line, repaired: false })
  })

  it('splits a self-intersecting (bowtie) polygon into a MultiPolygon', () => {
    const bowtie = {
      type: 'Polygon' as const,
      coordinates: [
        [
          [0, 0],
          [2, 2],
          [2, 0],
          [0, 2],
          [0, 0],
        ],
      ],
    }

    const result = repairSelfIntersection(bowtie)

    expect(result.repaired).toBe(true)
    expect(result.geometry.type).toBe('MultiPolygon')
    expect(
      (result.geometry as { coordinates: unknown[] }).coordinates,
    ).toHaveLength(2)
  })
})
