<?php

declare(strict_types=1);

namespace App\Tests\Functional\Controller;

use App\Tests\Functional\AppWebTestCase;

class SpaControllerTest extends AppWebTestCase
{
    // SPA-01: authenticated GET / → 200 with injected user data
    public function test_spa_renders_with_user_data_for_authenticated_user(): void
    {
        $user = $this->createUser('spatest@example.com');
        $this->loginAs($user);

        $this->client->request('GET', '/');

        $this->assertResponseIsSuccessful();
        $content = $this->client->getResponse()->getContent();
        $this->assertStringContainsString('window.__PF_USER__', $content);
        $this->assertStringContainsString('spatest@example.com', $content);
    }

    // SPA-02: unauthenticated GET / → redirect to /login
    public function test_spa_redirects_unauthenticated_to_login(): void
    {
        $this->client->request('GET', '/');
        $this->assertResponseRedirects('/login');
    }

    // SPA-03: authenticated GET /some/nested/path → still serves SPA
    public function test_spa_serves_nested_paths(): void
    {
        $user = $this->createUser('spatest2@example.com');
        $this->loginAs($user);

        $this->client->request('GET', '/library');

        $this->assertResponseIsSuccessful();
    }

    // SPA-04: authenticated GET / when index.html is absent → 404
    public function test_spa_throws_404_when_not_built(): void
    {
        $projectDir = static::getContainer()->getParameter('kernel.project_dir');
        $indexFile  = $projectDir . '/public/build/index.html';
        $tmpFile    = $indexFile . '.bak';

        $user = $this->createUser('spa04@example.com');
        $this->loginAs($user);

        rename($indexFile, $tmpFile);
        try {
            $this->client->request('GET', '/');
            $this->assertResponseStatusCodeSame(404);
        } finally {
            rename($tmpFile, $indexFile);
        }
    }
}
