<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Post;
use App\Administration\Application\Command\CreateClass\CreateClassHandler;
use App\Administration\Domain\Model\SchoolClass\ClassStatus;
use App\Administration\Infrastructure\Api\Processor\CreateClassProcessor;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryClassRepository;
use App\Administration\Infrastructure\Security\ClassVoter;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
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 CreateClassProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440002';

    private InMemoryClassRepository $classRepository;
    private TenantContext $tenantContext;
    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');
            }
        };

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

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

        $data = new ClassResource();
        $data->name = 'CM2-A';
        $data->level = 'CM2';
        $data->capacity = 30;

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

        self::assertNotNull($result->id);
        self::assertSame('CM2-A', $result->name);
        self::assertSame('CM2', $result->level);
        self::assertSame(30, $result->capacity);
        self::assertSame(ClassStatus::ACTIVE->value, $result->status);
    }

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

        $data = new ClassResource();
        $data->name = 'CP-B';
        $data->level = null;
        $data->capacity = null;

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

        self::assertNotNull($result->id);
        self::assertSame('CP-B', $result->name);
        self::assertNull($result->level);
        self::assertNull($result->capacity);
    }

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

        $data = new ClassResource();
        $data->name = 'CM2-A';
        $data->level = 'CM2';
        $data->capacity = 30;

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

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

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

        $data = new ClassResource();
        $data->name = 'CM2-A';
        $data->level = 'CM2';
        $data->capacity = 30;

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

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

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

        $data = new ClassResource();
        $data->name = 'CM2-A';
        $data->level = 'CM2';
        $data->capacity = 30;

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

        // Try to create a duplicate
        $this->expectException(ConflictHttpException::class);

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

    private function createProcessor(
        bool $authorized = true,
        ?TenantContext $tenantContext = null,
    ): CreateClassProcessor {
        $handler = new CreateClassHandler($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')
            ->with(ClassVoter::CREATE)
            ->willReturn($authorized);

        $resolvedTenantContext = $tenantContext ?? $this->tenantContext;

        $academicYearResolver = new CurrentAcademicYearResolver(
            $resolvedTenantContext,
            $this->clock,
        );

        return new CreateClassProcessor(
            $handler,
            $resolvedTenantContext,
            $eventBus,
            $authorizationChecker,
            $academicYearResolver,
        );
    }
}
