<?php

declare(strict_types=1);

namespace App\Tests\Unit\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Patch;
use App\Administration\Application\Command\UpdateClass\UpdateClassHandler;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\ClassName;
use App\Administration\Domain\Model\SchoolClass\SchoolClass;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
use App\Administration\Infrastructure\Api\Processor\UpdateClassProcessor;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryClassRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class UpdateClassProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440002';
    private const string SCHOOL_ID = '550e8400-e29b-41d4-a716-446655440003';
    private const string ACADEMIC_YEAR_ID = '550e8400-e29b-41d4-a716-446655440004';

    private InMemoryClassRepository $classRepository;
    private Clock $clock;

    protected function setUp(): void
    {
        $this->classRepository = new InMemoryClassRepository();
        $this->clock = new class implements Clock {
            public function now(): DateTimeImmutable
            {
                return new DateTimeImmutable('2026-02-10 10:00:00');
            }
        };
    }

    #[Test]
    public function updatesClassNameSuccessfully(): void
    {
        $class = $this->createAndSaveClass('CM2-A');
        $processor = $this->createProcessor();

        $data = new ClassResource();
        $data->name = 'CM2-B';

        $result = $processor->process($data, new Patch(), ['id' => (string) $class->id]);

        self::assertSame('CM2-B', $result->name);
    }

    #[Test]
    public function throwsWhenClassIdIsMissing(): void
    {
        $processor = $this->createProcessor();

        $data = new ClassResource();
        $data->name = 'CM2-B';

        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('ID de classe manquant');

        $processor->process($data, new Patch(), []);
    }

    #[Test]
    public function throwsWhenClassNotFound(): void
    {
        $processor = $this->createProcessor();

        $data = new ClassResource();
        $data->name = 'CM2-B';

        $this->expectException(NotFoundHttpException::class);

        $processor->process($data, new Patch(), ['id' => '550e8400-e29b-41d4-a716-446655440099']);
    }

    #[Test]
    public function throwsWhenNotAuthorized(): void
    {
        $class = $this->createAndSaveClass('CM2-A');
        $processor = $this->createProcessor(authorized: false);

        $data = new ClassResource();
        $data->name = 'CM2-B';

        $this->expectException(AccessDeniedHttpException::class);

        $processor->process($data, new Patch(), ['id' => (string) $class->id]);
    }

    #[Test]
    public function updatesCapacityAndLevel(): void
    {
        $class = $this->createAndSaveClass('CM2-A');
        $processor = $this->createProcessor();

        $data = new ClassResource();
        $data->level = 'CE1';
        $data->capacity = 25;

        $result = $processor->process($data, new Patch(), ['id' => (string) $class->id]);

        self::assertSame('CE1', $result->level);
        self::assertSame(25, $result->capacity);
    }

    private function createAndSaveClass(string $name): SchoolClass
    {
        $class = SchoolClass::creer(
            tenantId: TenantId::fromString(self::TENANT_ID),
            schoolId: SchoolId::fromString(self::SCHOOL_ID),
            academicYearId: AcademicYearId::fromString(self::ACADEMIC_YEAR_ID),
            name: new ClassName($name),
            level: null,
            capacity: 30,
            createdAt: new DateTimeImmutable('2026-02-01'),
        );
        $class->pullDomainEvents();
        $this->classRepository->save($class);

        return $class;
    }

    private function createProcessor(bool $authorized = true): UpdateClassProcessor
    {
        $handler = new UpdateClassHandler($this->classRepository, $this->clock);

        $eventBus = $this->createMock(MessageBusInterface::class);
        $eventBus->method('dispatch')->willReturnCallback(
            static fn (object $message) => new Envelope($message),
        );

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker->method('isGranted')->willReturn($authorized);

        return new UpdateClassProcessor(
            $handler,
            $this->classRepository,
            $eventBus,
            $authorizationChecker,
        );
    }
}
