<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Post;
use App\Administration\Application\Command\InviteUser\InviteUserHandler;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\StatutCompte;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Infrastructure\Api\Processor\InviteUserProcessor;
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\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Tests for InviteUserProcessor - ensuring the API layer correctly
 * handles both `roles` (array) and `role` (singular) payloads.
 *
 * Background: Story 2.6 introduced multi-role support where the frontend
 * sends `roles: ["ROLE_PROF"]` instead of `role: "ROLE_PROF"`.
 * The processor must derive `role` from `roles[0]` when `role` is absent.
 */
final class InviteUserProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440002';
    private const string SUBDOMAIN = 'ecole-alpha';

    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: self::SUBDOMAIN,
            databaseUrl: 'postgresql://test',
        ));
    }

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

        $data = new UserResource();
        $data->email = 'prof@example.com';
        $data->roles = [Role::PROF->value];
        $data->firstName = 'Marie';
        $data->lastName = 'Curie';
        // role is intentionally NOT set — this is the frontend behavior since Story 2.6

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

        self::assertSame('prof@example.com', $result->email);
        self::assertSame(Role::PROF->value, $result->role);
        self::assertSame([Role::PROF->value], $result->roles);
        self::assertSame(StatutCompte::EN_ATTENTE->value, $result->statut);
    }

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

        $data = new UserResource();
        $data->email = 'admin-prof@example.com';
        $data->roles = [Role::ADMIN->value, Role::PROF->value];
        $data->firstName = 'Albert';
        $data->lastName = 'Einstein';

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

        self::assertSame(Role::ADMIN->value, $result->role);
        self::assertSame([Role::ADMIN->value, Role::PROF->value], $result->roles);
    }

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

        $data = new UserResource();
        $data->email = 'legacy@example.com';
        $data->role = Role::PROF->value;
        $data->roles = [];
        $data->firstName = 'Isaac';
        $data->lastName = 'Newton';

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

        self::assertSame(Role::PROF->value, $result->role);
        self::assertSame([Role::PROF->value], $result->roles);
    }

    private function createProcessor(): InviteUserProcessor
    {
        $handler = new InviteUserHandler($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::CREATE)
            ->willReturn(true);

        $securityUser = new SecurityUser(
            userId: UserId::generate(),
            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 InviteUserProcessor(
            $handler,
            $this->tenantContext,
            $eventBus,
            $authorizationChecker,
            $this->clock,
            $security,
        );
    }
}
