<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ApiDocControllerTest extends WebTestCase
{
    public function testDocPageReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/api/doc');

        self::assertResponseIsSuccessful();
        self::assertSelectorExists('#env-switcher');
    }

    public function testSpecJsonReturnsJson(): void
    {
        $client = static::createClient();
        $client->request('GET', '/api/doc/spec.json');

        self::assertResponseIsSuccessful();
        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertIsArray($data);
        self::assertCount(5, $data);
        self::assertSame('Authentification', $data[0]['name']);
    }

    public function testInsomniaExportDownloads(): void
    {
        $client = static::createClient();
        $client->request('GET', '/api/doc/insomnia.json');

        self::assertResponseIsSuccessful();
        self::assertStringContainsString('attachment', $client->getResponse()->headers->get('Content-Disposition'));

        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertSame('export', $data['_type']);
        self::assertSame(4, $data['__export_format']);
        self::assertNotEmpty($data['resources']);
    }

    public function testInsomniaContainsWorkspaceAndEnv(): void
    {
        $client = static::createClient();
        $client->request('GET', '/api/doc/insomnia.json');

        $data = json_decode($client->getResponse()->getContent(), true);
        $types = array_column($data['resources'], '_type');

        self::assertContains('workspace', $types);
        self::assertContains('environment', $types);
        self::assertContains('request_group', $types);
        self::assertContains('request', $types);
    }

    public function testInsomniaLoginHasAfterResponseScript(): void
    {
        $client = static::createClient();
        $client->request('GET', '/api/doc/insomnia.json');

        $data = json_decode($client->getResponse()->getContent(), true);
        $requests = array_filter($data['resources'], fn ($r) => 'request' === ($r['_type'] ?? ''));

        $loginReq = null;
        foreach ($requests as $req) {
            if (str_contains($req['url'] ?? '', '/api/auth/login') && !str_contains($req['url'] ?? '', 'sso')) {
                $loginReq = $req;
                break;
            }
        }

        self::assertNotNull($loginReq);
        self::assertArrayHasKey('afterResponseScript', $loginReq);
        self::assertStringContainsString('jwt_token', $loginReq['afterResponseScript']);
    }
}
