<?php

declare(strict_types=1);

namespace App\Tests\Mcp\Tool\Slot;

use App\Tests\AbstractApiTestCase;

/**
 * @internal
 */
class SlotsToolTest extends AbstractApiTestCase
{
    public function testListSlotsForComposant(): void
    {
        $composant = $this->createComposant(name: 'Comp Slots');
        $this->createComposantPieceSlot(composant: $composant, position: 0);
        $this->createComposantProductSlot(composant: $composant, position: 1);
        $this->createComposantSubcomponentSlot(composant: $composant, alias: 'Sub A', position: 2);

        $session = $this->createMcpClient('ROLE_VIEWER');

        $data = $this->callMcpTool($session, 'list_slots', [
            'entityType' => 'composant',
            'entityId'   => $composant->getId(),
        ]);

        $this->assertArrayHasKey('_parsed', $data);
        $parsed = $data['_parsed'];
        $this->assertSame('composant', $parsed['entityType']);
        $this->assertSame(3, $parsed['total']);

        $slotTypes = array_column($parsed['slots'], 'slotType');
        $this->assertContains('piece', $slotTypes);
        $this->assertContains('product', $slotTypes);
        $this->assertContains('subcomponent', $slotTypes);
    }

    public function testListSlotsForPiece(): void
    {
        $piece = $this->createPiece(name: 'Piece Slots');
        $this->createPieceProductSlot(piece: $piece, position: 0);
        $this->createPieceProductSlot(piece: $piece, position: 1);

        $session = $this->createMcpClient('ROLE_VIEWER');

        $data = $this->callMcpTool($session, 'list_slots', [
            'entityType' => 'piece',
            'entityId'   => $piece->getId(),
        ]);

        $this->assertArrayHasKey('_parsed', $data);
        $parsed = $data['_parsed'];
        $this->assertSame('piece', $parsed['entityType']);
        $this->assertSame(2, $parsed['total']);

        foreach ($parsed['slots'] as $slot) {
            $this->assertSame('product', $slot['slotType']);
        }
    }

    public function testUpdateSlotSelectsPiece(): void
    {
        $composant = $this->createComposant(name: 'Comp Update');
        $piece     = $this->createPiece(name: 'Selected Piece');
        $slot      = $this->createComposantPieceSlot(composant: $composant, position: 0);

        $session = $this->createMcpClient('ROLE_GESTIONNAIRE');

        $data = $this->callMcpTool($session, 'update_slots', [
            'slots' => [
                [
                    'slotId'          => $slot->getId(),
                    'slotType'        => 'composant_piece',
                    'selectedPieceId' => $piece->getId(),
                ],
            ],
        ]);

        $this->assertArrayHasKey('_parsed', $data);
        $parsed = $data['_parsed'];
        $this->assertSame(1, $parsed['total']);
        $this->assertSame($piece->getId(), $parsed['updated'][0]['selectedEntityId']);
        $this->assertSame('Selected Piece', $parsed['updated'][0]['selectedEntityName']);
    }
}
