package space.nstart.pcp.complan.apl

import org.junit.jupiter.api.Test
import org.locationtech.jts.geom.Polygon
import org.locationtech.jts.io.WKTReader
import space.nstart.pcp.pcp_types_lib.dto.ballistics.OrbPointDTO
import java.time.LocalDateTime
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue

class SurveyContourBuilderTest {

    private val builder = SurveyContourBuilder()

    @Test
    fun `build returns closed polygon contour for orbital points`() {
        val contour = builder.build(
            points = sampleOrbitalPoints(),
            roll = 5.0,
            capture = 1.5
        )

        assertNotNull(contour)
        val geometry = WKTReader().read(contour)
        assertTrue(geometry is Polygon)
        assertTrue(geometry.isValid)
        assertEquals(geometry.coordinates.first(), geometry.coordinates.last())
    }

    @Test
    fun `build returns null when orbital points are not enough`() {
        val contour = builder.build(
            points = sampleOrbitalPoints().take(1),
            roll = 5.0,
            capture = 1.5
        )

        assertNull(contour)
    }

    private fun sampleOrbitalPoints() = listOf(
        orbPoint(
            time = LocalDateTime.of(2026, 4, 14, 10, 0),
            revolution = 42L,
            x = -6603039.949,
            y = -1870023.148,
            z = 0.0,
            vx = -401.529,
            vy = 1413.431,
            vz = 7547.696
        ),
        orbPoint(
            time = LocalDateTime.of(2026, 4, 14, 10, 1),
            revolution = 42L,
            x = -6595000.0,
            y = -1860000.0,
            z = 452000.0,
            vx = -420.0,
            vy = 1390.0,
            vz = 7540.0
        )
    )

    private fun orbPoint(
        time: LocalDateTime,
        revolution: Long,
        x: Double,
        y: Double,
        z: Double,
        vx: Double,
        vy: Double,
        vz: Double
    ) = OrbPointDTO(
        time = time,
        revolution = revolution,
        vx = vx,
        vy = vy,
        vz = vz,
        x = x,
        y = y,
        z = z
    )
}
