<?php

declare(strict_types=1);

namespace Apexl\Tests\User\FeatureTests;

use apexl\Io\includes\RouteManager;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\TestInfrastructure\FeatureTest;
use apexl\Vault\enums\SortDirection;
use PHPUnit\Framework\Attributes\Test;
use function apexl\Io\container;

final class RegisterTest extends FeatureTest
{
    #[Test]
    public function register(): void
    {
        $email = $this->faker->email();
        $password = $this->faker->password();

        $data = $this->post('/api/v1/user/action/register', [
            'first_name' => $this->faker->firstName(),
            'last_name' => $this->faker->lastName(),
            'email' => $email,
            'password' => $password,
            'password_confirm' => $password,
        ]);

        $this->assertArrayHasKey('redirect', $data);

        $this->assertSame(
            container()->get(RouteManager::class)->getRoutePattern('user.display.login'),
            $data['redirect'],
        );

        $result = new userEntity()->loadMultiple(
            orderBy: ['created', SortDirection::DESC->name],
            limit: 1
        );

        $user = array_pop($result);

        $this->assertSame($email, $user->email);
        $this->assertTrue(password_verify($password, $user->password));
    }

    #[Test]
    public function duplicateUser(): void
    {
        $email = $this->faker->email();

        userEntity::factory()->create([
            'email' => $email,
        ]);

        $password = $this->faker->password();

        $this->post('/api/v1/user/action/register', [
            'first_name' => $this->faker->firstName(),
            'last_name' => $this->faker->lastName(),
            'email' => $email,
            'password' => $password,
            'password_confirm' => $password,
        ], 422);
    }

    #[Test]
    public function missingDataInRequest(): void
    {
        $password = $this->faker->password();

        $data = [
            'first_name' => $this->faker->firstName(),
            'last_name' => $this->faker->lastName(),
            'email' => $this->faker->email(),
            'password' => $password,
            'password_confirm' => $password,
        ];

        foreach ($data as $key => $value) {
            $_data = [...$data];
            unset($_data[$key]);

            $response = $this->post('/api/v1/user/action/register', $_data, 422);

            $this->assertArrayHasKey($key, $response);
        }
    }

}
