<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Post;
use App\Administration\Application\Command\BlockUser\BlockUserHandler;
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\BlockUserProcessor;
use App\Administration\Infrastructure\Api\Resource\UserResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryUserRepository;
use App\Administration\Infrastructure\Security\SecurityUser;
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\Bundle\SecurityBundle\Security;
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 BlockUserProcessorTest 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 blocksUserSuccessfully(): void
    {
        $user = $this->createActiveUser();
        $processor = $this->createProcessor(adminUserId: (string) UserId::generate());

        $data = new UserResource();
        $data->reason = 'Comportement inapproprié';

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

        self::assertSame(StatutCompte::SUSPENDU->value, $result->statut);
        self::assertSame('Comportement inapproprié', $result->blockedReason);
    }

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

        $data = new UserResource();
        $data->reason = 'Some reason';

        $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();
        $data->reason = 'Some reason';

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

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

    #[Test]
    public function throwsWhenBlockingOwnAccount(): void
    {
        $adminId = UserId::generate();
        $processor = $this->createProcessor(adminUserId: (string) $adminId);

        $data = new UserResource();
        $data->reason = 'Self-block attempt';

        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('propre compte');

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

    #[Test]
    public function throwsWhenReasonIsEmpty(): void
    {
        $processor = $this->createProcessor(adminUserId: (string) UserId::generate());

        $data = new UserResource();
        $data->reason = '';

        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('raison du blocage est obligatoire');

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

    #[Test]
    public function throwsWhenReasonIsOnlyWhitespace(): void
    {
        $processor = $this->createProcessor(adminUserId: (string) UserId::generate());

        $data = new UserResource();
        $data->reason = '   ';

        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('raison du blocage est obligatoire');

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

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

        $data = new UserResource();
        $data->reason = 'Some reason';

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

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

    #[Test]
    public function throwsWhenUserIsNotBlockable(): void
    {
        // Create a user in EN_ATTENTE status (not active, so can't be blocked)
        $user = User::inviter(
            email: new Email('pending@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();
        $this->userRepository->save($user);

        $processor = $this->createProcessor(adminUserId: (string) UserId::generate());

        $data = new UserResource();
        $data->reason = 'Trying to block pending user';

        $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('teacher@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 createProcessor(
        bool $authorized = true,
        string $adminUserId = '',
        ?TenantContext $tenantContext = null,
    ): BlockUserProcessor {
        $handler = new BlockUserHandler($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::BLOCK)
            ->willReturn($authorized);

        if ($adminUserId === '') {
            $adminUserId = (string) UserId::generate();
        }

        $securityUser = new SecurityUser(
            userId: UserId::fromString($adminUserId),
            email: 'admin@example.com',
            hashedPassword: '$argon2id$hashed',
            tenantId: TenantId::fromString(self::TENANT_ID),
            roles: [Role::ADMIN->value],
        );

        $security = $this->createMock(Security::class);
        $security->method('getUser')->willReturn($securityUser);

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