<?php

namespace Tests\Feature;

use App\Services\SpatialFileConverter;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;

class SpatialFileConverterTest extends TestCase
{
    private function uploadedKml(string $content, string $name = 'test.kml'): UploadedFile
    {
        $tmp = tempnam(sys_get_temp_dir(), 'kml_');
        file_put_contents($tmp, $content);

        return new UploadedFile($tmp, $name, 'application/vnd.google-earth.kml+xml', null, true);
    }

    public function test_kml_with_opengis_namespace_yields_features(): void
    {
        $kml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Placemark><name>P1</name><Point><coordinates>-3.7,40.4,0</coordinates></Point></Placemark>
    <Placemark><name>P2</name><Point><coordinates>-3.6,40.5,0</coordinates></Point></Placemark>
  </Document>
</kml>';
        $g = SpatialFileConverter::convertToGeoJson($this->uploadedKml($kml));
        $this->assertNotNull($g);
        $this->assertCount(2, $g['features']);
        $this->assertEquals('Point', $g['features'][0]['geometry']['type']);
    }

    public function test_kml_with_google_earth_namespace_still_yields_features(): void
    {
        // Este era el bug: xpath //kml:Placemark fallaba con este xmlns.
        $kml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
  <Document>
    <Placemark><name>Pilar 1</name><Point><coordinates>-3.7,40.4</coordinates></Point></Placemark>
  </Document>
</kml>';
        $g = SpatialFileConverter::convertToGeoJson($this->uploadedKml($kml));
        $this->assertNotNull($g);
        $this->assertCount(1, $g['features']);
        $this->assertEquals('Pilar 1', $g['features'][0]['properties']['name']);
    }

    public function test_kml_without_namespace_still_yields_features(): void
    {
        $kml = '<?xml version="1.0" encoding="UTF-8"?>
<kml>
  <Placemark><name>Muro</name>
    <LineString><coordinates>-3.7,40.4 -3.6,40.5</coordinates></LineString>
  </Placemark>
</kml>';
        $g = SpatialFileConverter::convertToGeoJson($this->uploadedKml($kml));
        $this->assertNotNull($g);
        $this->assertCount(1, $g['features']);
        $this->assertEquals('LineString', $g['features'][0]['geometry']['type']);
    }
}
