<?php

declare(strict_types=1);

namespace App\Tests\Unit\Administration\Infrastructure\Security;

use App\Administration\Infrastructure\Security\JwtPayloadEnricher;
use App\SuperAdmin\Domain\Model\SuperAdmin\SuperAdminId;
use App\SuperAdmin\Infrastructure\Security\SecuritySuperAdmin;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

final class JwtPayloadEnricherSuperAdminTest extends TestCase
{
    private JwtPayloadEnricher $enricher;

    protected function setUp(): void
    {
        $this->enricher = new JwtPayloadEnricher();
    }

    #[Test]
    public function onJWTCreatedAddsSuperAdminClaimsToPayload(): void
    {
        $superAdminId = SuperAdminId::generate();

        $securitySuperAdmin = new SecuritySuperAdmin(
            superAdminId: $superAdminId,
            email: 'sadmin@test.com',
            hashedPassword: 'hashed',
        );

        $initialPayload = ['username' => 'sadmin@test.com'];
        $event = new JWTCreatedEvent($initialPayload, $securitySuperAdmin);

        $this->enricher->onJWTCreated($event);

        $payload = $event->getData();

        self::assertSame((string) $superAdminId, $payload['user_id']);
        self::assertSame('super_admin', $payload['user_type']);
        self::assertSame(['ROLE_SUPER_ADMIN'], $payload['roles']);
        self::assertArrayNotHasKey('tenant_id', $payload);
    }

    #[Test]
    public function onJWTCreatedPreservesExistingPayloadForSuperAdmin(): void
    {
        $securitySuperAdmin = new SecuritySuperAdmin(
            superAdminId: SuperAdminId::generate(),
            email: 'sadmin@test.com',
            hashedPassword: 'hashed',
        );

        $initialPayload = [
            'username' => 'sadmin@test.com',
            'iat' => 1706436600,
            'exp' => 1706438400,
        ];
        $event = new JWTCreatedEvent($initialPayload, $securitySuperAdmin);

        $this->enricher->onJWTCreated($event);

        $payload = $event->getData();

        self::assertSame('sadmin@test.com', $payload['username']);
        self::assertSame(1706436600, $payload['iat']);
        self::assertSame(1706438400, $payload['exp']);
    }
}
