<?php

declare(strict_types=1);

namespace App\Tests\Mcp\Security;

use App\Tests\AbstractApiTestCase;
use stdClass;

/**
 * @internal
 */
class McpHeaderAuthenticatorTest extends AbstractApiTestCase
{
    public function testMcpEndpointRejectsWithoutCredentials(): void
    {
        $client = static::createClient();

        $client->request('POST', '/_mcp', [
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => $this->mcpRequest(),
        ]);

        $this->assertResponseStatusCodeSame(401);
    }

    public function testMcpEndpointRejectsInvalidPassword(): void
    {
        $profile = $this->createProfile(
            roles: ['ROLE_VIEWER'],
            password: 'correct-password',
        );

        $client = static::createClient();

        $client->request('POST', '/_mcp', [
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Profile-Id'       => $profile->getId(),
                'X-Profile-Password' => 'wrong-password',
            ],
            'body' => $this->mcpRequest(),
        ]);

        $this->assertResponseStatusCodeSame(401);
    }

    public function testMcpEndpointAcceptsValidCredentials(): void
    {
        $profile = $this->createProfile(
            roles: ['ROLE_VIEWER'],
            password: 'valid-password',
        );

        $client = static::createClient();

        $client->request('POST', '/_mcp', [
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Profile-Id'       => $profile->getId(),
                'X-Profile-Password' => 'valid-password',
            ],
            'body' => $this->mcpRequest(),
        ]);

        $this->assertResponseStatusCodeSame(200);
    }

    private function mcpRequest(array $headers = [], array $body = []): string
    {
        $default = [
            'jsonrpc' => '2.0',
            'method'  => 'initialize',
            'params'  => [
                'protocolVersion' => '2025-03-26',
                'capabilities'    => new stdClass(),
                'clientInfo'      => ['name' => 'test', 'version' => '1.0'],
            ],
            'id' => 1,
        ];

        return json_encode(array_merge($default, $body));
    }
}
