<?php

declare(strict_types=1);

namespace App\Tests\Mcp\Tool\Site;

use App\Tests\AbstractApiTestCase;

/**
 * @internal
 */
class SitesCrudToolTest extends AbstractApiTestCase
{
    public function testListSites(): void
    {
        $this->createSite(name: 'Site Alpha');
        $this->createSite(name: 'Site Beta');
        $session = $this->createMcpClient('ROLE_VIEWER');

        $data = $this->callMcpTool($session, 'list_sites');

        $this->assertArrayHasKey('_parsed', $data);
        $this->assertGreaterThanOrEqual(2, $data['_parsed']['total']);
    }

    public function testGetSite(): void
    {
        $site    = $this->createSite(name: 'Site Gamma');
        $session = $this->createMcpClient('ROLE_VIEWER');

        $data = $this->callMcpTool($session, 'get_site', ['siteId' => $site->getId()]);

        $this->assertArrayHasKey('_parsed', $data);
        $this->assertSame('Site Gamma', $data['_parsed']['name']);
    }

    public function testCreateSite(): void
    {
        $session = $this->createMcpClient('ROLE_GESTIONNAIRE');

        $data = $this->callMcpTool($session, 'create_site', [
            'name'        => 'Site Nouveau',
            'contactCity' => 'Paris',
        ]);

        $this->assertArrayHasKey('_parsed', $data);
        $this->assertSame('Site Nouveau', $data['_parsed']['name']);
        $this->assertNotEmpty($data['_parsed']['id']);
    }

    public function testCreateSiteRequiresGestionnaire(): void
    {
        $session = $this->createMcpClient('ROLE_VIEWER');

        $data = $this->callMcpTool($session, 'create_site', ['name' => 'Forbidden']);

        $this->assertArrayHasKey('error', $data);
    }

    public function testUpdateSite(): void
    {
        $site    = $this->createSite(name: 'Old Name');
        $session = $this->createMcpClient('ROLE_GESTIONNAIRE');

        $data = $this->callMcpTool($session, 'update_site', [
            'siteId' => $site->getId(),
            'name'   => 'New Name',
        ]);

        $this->assertArrayHasKey('_parsed', $data);
        $this->assertSame('New Name', $data['_parsed']['name']);
    }

    public function testDeleteSite(): void
    {
        $site    = $this->createSite(name: 'To Delete');
        $session = $this->createMcpClient('ROLE_GESTIONNAIRE');

        $data = $this->callMcpTool($session, 'delete_site', ['siteId' => $site->getId()]);

        $this->assertArrayHasKey('_parsed', $data);
        $this->assertTrue($data['_parsed']['deleted']);
    }
}
