<?php

declare(strict_types=1);

namespace Tests\Feature\Pwa;

use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

/**
 * Tests para GET /pwa/version.
 *
 * El endpoint sirve public/build/version.json (generado por Vite) y degrada a
 * un payload "dev/unknown" si el archivo no existe (entorno sin build).
 */
class PwaVersionTest extends TestCase
{
    private string $path;

    private ?string $original = null;

    protected function setUp(): void
    {
        parent::setUp();

        $this->path = public_path('build/version.json');
        $this->original = is_file($this->path) ? (string) file_get_contents($this->path) : null;
    }

    protected function tearDown(): void
    {
        if ($this->original !== null) {
            file_put_contents($this->path, $this->original);
        } elseif (is_file($this->path)) {
            unlink($this->path);
        }

        parent::tearDown();
    }

    #[Test]
    public function it_returns_the_build_version_from_the_generated_file(): void
    {
        if (! is_dir(dirname($this->path))) {
            mkdir(dirname($this->path), 0775, true);
        }

        file_put_contents($this->path, json_encode([
            'version' => '2026-06-18-abc1234',
            'commit' => 'abc1234',
            'builtAt' => '2026-06-18T12:00:00.000Z',
        ]));

        $this->getJson('/pwa/version')
            ->assertOk()
            ->assertExactJson([
                'version' => '2026-06-18-abc1234',
                'commit' => 'abc1234',
                'builtAt' => '2026-06-18T12:00:00.000Z',
            ]);
    }

    #[Test]
    public function it_degrades_gracefully_when_the_version_file_is_missing(): void
    {
        if (is_file($this->path)) {
            unlink($this->path);
        }

        $this->getJson('/pwa/version')
            ->assertOk()
            ->assertJson([
                'version' => 'dev',
                'commit' => 'unknown',
                'builtAt' => null,
            ]);
    }
}
