<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Post;
use App\Administration\Application\Command\CreateSubject\CreateSubjectHandler;
use App\Administration\Infrastructure\Api\Processor\CreateSubjectProcessor;
use App\Administration\Infrastructure\Api\Resource\SubjectResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemorySubjectRepository;
use App\Administration\Infrastructure\School\SchoolIdResolver;
use App\Administration\Infrastructure\Security\SubjectVoter;
use App\Shared\Domain\Clock;
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\ConflictHttpException;
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 CreateSubjectProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440002';

    private InMemorySubjectRepository $subjectRepository;
    private TenantContext $tenantContext;
    private Clock $clock;

    protected function setUp(): void
    {
        $this->subjectRepository = new InMemorySubjectRepository();
        $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 createsSubjectSuccessfully(): void
    {
        $processor = $this->createProcessor();

        $data = new SubjectResource();
        $data->name = 'Mathématiques';
        $data->code = 'MATH';
        $data->color = '#FF5733';

        $result = $processor->process($data, new Post());

        self::assertNotNull($result->id);
        self::assertSame('Mathématiques', $result->name);
        self::assertSame('MATH', $result->code);
        self::assertSame('#FF5733', $result->color);
    }

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

        $data = new SubjectResource();
        $data->name = 'Français';
        $data->code = 'FR';
        $data->color = null;

        $result = $processor->process($data, new Post());

        self::assertNotNull($result->id);
        self::assertSame('Français', $result->name);
        self::assertSame('FR', $result->code);
        self::assertNull($result->color);
    }

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

        $data = new SubjectResource();
        $data->name = 'Mathématiques';
        $data->code = 'MATH';
        $data->color = null;

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

        $processor->process($data, new Post());
    }

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

        $data = new SubjectResource();
        $data->name = 'Mathématiques';
        $data->code = 'MATH';
        $data->color = null;

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

        $processor->process($data, new Post());
    }

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

        $data = new SubjectResource();
        $data->name = 'Mathématiques';
        $data->code = 'MATH';
        $data->color = null;

        // Create the first subject
        $processor->process($data, new Post());

        // Try to create a duplicate code
        $data2 = new SubjectResource();
        $data2->name = 'Maths avancées';
        $data2->code = 'MATH';
        $data2->color = null;

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

        $processor->process($data2, new Post());
    }

    private function createProcessor(
        bool $authorized = true,
        ?TenantContext $tenantContext = null,
    ): CreateSubjectProcessor {
        $handler = new CreateSubjectHandler($this->subjectRepository, $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(SubjectVoter::CREATE)
            ->willReturn($authorized);

        $schoolIdResolver = new SchoolIdResolver();

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