<?php

declare(strict_types=1);

namespace Apexl\Tests\User\FeatureTests;

use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\TestInfrastructure\FeatureTest;
use PHPUnit\Framework\Attributes\Test;

final class LoginWithKeyTest extends FeatureTest
{
    public static function setUpBeforeClass(): void
    {
        $_ENV['AUTH_ENABLE_QUERY_STRING_LOGIN'] = true;
        parent::setUpBeforeClass(); // TODO: Change the autogenerated stub
    }

    #[Test]
    function InvalidKeyTest(): void
    {
        $this->post('/api/v1/user/action/login/nfc', [
            'nfc_key' => 'invalid-key'
        ], expectCode: 403);
    }

    #[Test]
    function ValidKeyTest(): void
    {
        $validKey = 'valid-key';
        userEntity::factory()->create([
            'nfc_key' => $validKey
        ]);

        $data = $this->post('/api/v1/user/action/login/nfc', [
            'nfc_key' => $validKey
        ]);

        $this->assertSuccessfulResponse($data);

        $redirect = '/foo';
        $data = $this->post('/api/v1/user/action/login/nfc', [
            'nfc_key' => $validKey,
            'redirect' => $redirect,
        ]);

        $this->assertSuccessfulResponse($data, $redirect);
    }

    private function assertSuccessfulResponse(array $data, string $expectedRedirect = '/'): void
    {
        $this->assertIsArray($data);
        $this->assertTrue($data['success']);
        $this->assertIsString($data['access_token']);
        $this->assertIsString($data['refresh_token']);
        $this->assertSame($expectedRedirect, $data['redirect']);
        $this->assertIsInt($data['expires_in']);

    }

    #[Test]
    function ValidKeyInactiveUserTest(): void
    {
        $validKey = 'valid-key';
        userEntity::factory()->create([
            'nfc_key' => $validKey,
            'active' => false,
        ]);

        $this->post('/api/v1/user/action/login/nfc', [
            'nfc_key' => $validKey
        ], expectCode: 401);
    }
}
