<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Post;
use App\Administration\Application\Command\UnblockUser\UnblockUserHandler;
use App\Administration\Domain\Model\User\Email;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\StatutCompte;
use App\Administration\Domain\Model\User\User;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Policy\ConsentementParentalPolicy;
use App\Administration\Infrastructure\Api\Processor\UnblockUserProcessor;
use App\Administration\Infrastructure\Api\Resource\UserResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryUserRepository;
use App\Administration\Infrastructure\Security\UserVoter;
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\BadRequestHttpException;
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 UnblockUserProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440002';

    private InMemoryUserRepository $userRepository;
    private TenantContext $tenantContext;
    private Clock $clock;

    protected function setUp(): void
    {
        $this->userRepository = new InMemoryUserRepository();
        $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 unblocksUserSuccessfully(): void
    {
        $user = $this->createBlockedUser();
        $processor = $this->createProcessor();

        $data = new UserResource();

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

        self::assertSame(StatutCompte::ACTIF->value, $result->statut);
        self::assertNull($result->blockedReason);
    }

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

        $data = new UserResource();

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

        $processor->process($data, new Post(), ['id' => (string) UserId::generate()]);
    }

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

        $data = new UserResource();

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

        $processor->process($data, new Post(), ['id' => (string) UserId::generate()]);
    }

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

        $data = new UserResource();

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

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

    #[Test]
    public function throwsWhenUserIsNotSuspended(): void
    {
        // Active user cannot be unblocked (only suspended ones)
        $user = $this->createActiveUser();
        $processor = $this->createProcessor();

        $data = new UserResource();

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

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

    private function createActiveUser(): User
    {
        $consentementPolicy = new ConsentementParentalPolicy($this->clock);

        $user = User::inviter(
            email: new Email('active@example.com'),
            role: Role::PROF,
            tenantId: TenantId::fromString(self::TENANT_ID),
            schoolName: 'École Alpha',
            firstName: 'Jean',
            lastName: 'Dupont',
            invitedAt: new DateTimeImmutable('2026-02-01'),
        );
        $user->pullDomainEvents();
        $user->activer('$argon2id$hashed', new DateTimeImmutable('2026-02-02'), $consentementPolicy);
        $user->pullDomainEvents();
        $this->userRepository->save($user);

        return $user;
    }

    private function createBlockedUser(): User
    {
        $user = $this->createActiveUser();
        $user->bloquer('Raison du blocage', new DateTimeImmutable('2026-02-09'));
        $user->pullDomainEvents();
        $this->userRepository->save($user);

        return $user;
    }

    private function createProcessor(
        bool $authorized = true,
        ?TenantContext $tenantContext = null,
    ): UnblockUserProcessor {
        $handler = new UnblockUserHandler($this->userRepository, $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(UserVoter::UNBLOCK)
            ->willReturn($authorized);

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