<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\TestInfrastructure;

use apexl\Io\enums\HttpMethod;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\enums\Role;

trait MakesAuthenticatedRequests
{
    protected function getAuthenticated(string $uri, ?int $expectCode = 200, array $headers = [], ?userEntity $user = null): array
    {
        return $this->executeAuthenticatedRequest(
            user: $user ?? $this->defaultSuperAdminUser(),
            method: HttpMethod::GET,
            uri: $uri,
            headers: $headers,
            expectCode: $expectCode,
        );
    }

    protected function executeAuthenticatedRequest(
        userEntity $user,
        HttpMethod $method,
        string $uri,
        array $body = [],
        array $headers = [],
        ?int $expectCode = 200
    ): array {
        $request = $this->request($method, $uri, $body, $headers)
            ->withAttribute('user', $user->id)
            ->withAttribute('authenticated', true);

        $response = self::$application->handle($request);

        return $this->responseToData($response, $expectCode);
    }

    private function defaultSuperAdminUser(): userEntity
    {
        $user = userEntity::factory()->create();
        $user->addRole(Role::SUPER_ADMINISTRATOR);

        return $user;
    }

}