<?php

declare(strict_types=1);

namespace Dalten\RuianToUir\Tests\Unit\Converter\Field;

use Dalten\RuianToUir\Converter\Field\PointCoordinatesConverter;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use proj4php\Proj;
use proj4php\Proj4php;

#[CoversClass(PointCoordinatesConverter::class)]
final class PointCoordinatesConverterTest extends TestCase
{
    public function testRoundTripsWgs84ToSjtSkAndBackWithinTolerance(): void
    {
        $proj4 = new Proj4php();
        $krovak = new Proj('EPSG:5514', $proj4);
        $wgs84 = new Proj('EPSG:4326', $proj4);

        $converter = new PointCoordinatesConverter($proj4, $krovak, $wgs84);

        // Choose a known WGS point (Prague Old Town Square)
        $lat = 50.087451; // N
        $lon = 14.420671; // E

        // Transform WGS84 -> S-JTSK using the same library
        $wgsPoint = new \proj4php\Point(sprintf('%f %f', $lon, $lat), null, null, $wgs84);
        $sjtskPoint = $proj4->transform($krovak, $wgsPoint);
        $this->assertInstanceOf(\proj4php\Point::class, $sjtskPoint);
        /** @var array{0: float, 1: float} $sjtsk */
        $sjtsk = $sjtskPoint->toArray();
        $inputForConverter = sprintf('%f %f', $sjtsk[0], $sjtsk[1]);

        // Now convert back using our class under test
        $out = $converter->convertCoords($inputForConverter);
        [$outLat, $outLon] = array_map('floatval', explode(' ', $out));

        $this->assertEqualsWithDelta($lat, $outLat, 1e-5, 'Latitude within tolerance');
        $this->assertEqualsWithDelta($lon, $outLon, 1e-5, 'Longitude within tolerance');
    }
}
