<?php

declare(strict_types=1);

use App\Framework\LiveComponents\Batch\BatchOperation;
use App\Framework\LiveComponents\Batch\BatchRequest;

describe('BatchRequest', function () {
    it('creates request with variadic constructor', function () {
        $op1 = new BatchOperation('counter:demo', 'increment');
        $op2 = new BatchOperation('stats:user', 'refresh');

        $request = new BatchRequest($op1, $op2);

        expect($request->operations)->toHaveCount(2);
        expect($request->operations[0])->toBe($op1);
        expect($request->operations[1])->toBe($op2);
    });

    it('creates request from array', function () {
        $data = [
            'operations' => [
                [
                    'componentId' => 'counter:demo',
                    'method' => 'increment',
                    'params' => ['amount' => 5],
                ],
                [
                    'componentId' => 'stats:user',
                    'method' => 'refresh',
                ],
            ],
        ];

        $request = BatchRequest::fromArray($data);

        expect($request->operations)->toHaveCount(2);
        expect($request->operations[0]->componentId)->toBe('counter:demo');
        expect($request->operations[1]->componentId)->toBe('stats:user');
    });

    it('throws on empty operations', function () {
        expect(fn () => new BatchRequest())
            ->toThrow(InvalidArgumentException::class, 'Batch request must contain at least one operation');
    });

    it('throws on too many operations', function () {
        $operations = [];
        for ($i = 0; $i < 51; $i++) {
            $operations[] = new BatchOperation("component:$i", 'method');
        }

        expect(fn () => new BatchRequest(...$operations))
            ->toThrow(InvalidArgumentException::class, 'Batch request cannot exceed 50 operations');
    });

    it('allows maximum 50 operations', function () {
        $operations = [];
        for ($i = 0; $i < 50; $i++) {
            $operations[] = new BatchOperation("component:$i", 'method');
        }

        $request = new BatchRequest(...$operations);

        expect($request->operations)->toHaveCount(50);
    });

    it('gets operations', function () {
        $op1 = new BatchOperation('counter:demo', 'increment');
        $op2 = new BatchOperation('stats:user', 'refresh');

        $request = new BatchRequest($op1, $op2);

        expect($request->getOperations())->toBe([$op1, $op2]);
    });

    it('counts operations', function () {
        $op1 = new BatchOperation('counter:demo', 'increment');
        $op2 = new BatchOperation('stats:user', 'refresh');
        $op3 = new BatchOperation('form:contact', 'submit');

        $request = new BatchRequest($op1, $op2, $op3);

        expect($request->count())->toBe(3);
    });
});
