<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Delete;
use App\Administration\Application\Command\RemoveAssignment\RemoveAssignmentHandler;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\TeacherAssignment\TeacherAssignment;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Infrastructure\Api\Processor\RemoveTeacherAssignmentProcessor;
use App\Administration\Infrastructure\Api\Resource\TeacherAssignmentResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryTeacherAssignmentRepository;
use App\Administration\Infrastructure\Security\TeacherAssignmentVoter;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantConfig;
use App\Shared\Infrastructure\Tenant\TenantContext;
use App\Shared\Infrastructure\Tenant\TenantId as InfraTenantId;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class RemoveTeacherAssignmentProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440002';
    private const string TEACHER_ID = '550e8400-e29b-41d4-a716-446655440010';
    private const string CLASS_ID = '550e8400-e29b-41d4-a716-446655440020';
    private const string SUBJECT_ID = '550e8400-e29b-41d4-a716-446655440030';
    private const string ACADEMIC_YEAR_ID = '550e8400-e29b-41d4-a716-446655440040';

    private InMemoryTeacherAssignmentRepository $repository;
    private TenantContext $tenantContext;
    private Clock $clock;

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

        $this->tenantContext = new TenantContext();
        $this->tenantContext->setCurrentTenant(new TenantConfig(
            tenantId: InfraTenantId::fromString(self::TENANT_ID),
            subdomain: 'ecole-alpha',
            databaseUrl: 'postgresql://test',
        ));
    }

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

        $result = $processor->process(
            new TeacherAssignmentResource(),
            new Delete(),
            uriVariables: ['id' => (string) $assignment->id],
        );

        self::assertNull($result);
    }

    #[Test]
    public function throwsWhenNotAuthorized(): void
    {
        $assignment = $this->createAndSaveAssignment();
        $processor = $this->createProcessor(authorized: false);

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

        $processor->process(
            new TeacherAssignmentResource(),
            new Delete(),
            uriVariables: ['id' => (string) $assignment->id],
        );
    }

    #[Test]
    public function throwsWhenTenantNotSet(): void
    {
        $assignment = $this->createAndSaveAssignment();
        $emptyTenantContext = new TenantContext();
        $processor = $this->createProcessor(tenantContext: $emptyTenantContext);

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

        $processor->process(
            new TeacherAssignmentResource(),
            new Delete(),
            uriVariables: ['id' => (string) $assignment->id],
        );
    }

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

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

        $processor->process(
            new TeacherAssignmentResource(),
            new Delete(),
            uriVariables: ['id' => '550e8400-e29b-41d4-a716-446655440099'],
        );
    }

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

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

        $processor->process(
            new TeacherAssignmentResource(),
            new Delete(),
        );
    }

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

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

        $processor->process(
            new TeacherAssignmentResource(),
            new Delete(),
            uriVariables: ['id' => 'not-a-uuid'],
        );
    }

    private function createAndSaveAssignment(): TeacherAssignment
    {
        $assignment = TeacherAssignment::creer(
            tenantId: TenantId::fromString(self::TENANT_ID),
            teacherId: UserId::fromString(self::TEACHER_ID),
            classId: ClassId::fromString(self::CLASS_ID),
            subjectId: SubjectId::fromString(self::SUBJECT_ID),
            academicYearId: AcademicYearId::fromString(self::ACADEMIC_YEAR_ID),
            createdAt: new DateTimeImmutable('2026-02-10 10:00:00'),
        );

        // Consommer les événements du domaine pour éviter les interférences
        $assignment->pullDomainEvents();

        $this->repository->save($assignment);

        return $assignment;
    }

    private function createProcessor(
        bool $authorized = true,
        ?TenantContext $tenantContext = null,
    ): RemoveTeacherAssignmentProcessor {
        $handler = new RemoveAssignmentHandler($this->repository, $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')
            ->with(TeacherAssignmentVoter::DELETE)
            ->willReturn($authorized);

        return new RemoveTeacherAssignmentProcessor(
            $handler,
            $tenantContext ?? $this->tenantContext,
            $eventBus,
            $authorizationChecker,
        );
    }
}
