<?php

namespace Modules\API\Authenticate\Controller;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use GuzzleHttp\Psr7\Response;
use Helpers\Securite\SecuriteIP;

final class AuthController extends AuthAbstractController implements \Modules\API\Authenticate\Controller\AuthInterfaceController
{

    /**
     * @var string $methode
     */
    protected string $methode;

    /**
     * @var array<mixed> $post
     */
    protected array $post;

    /**
     * @var \Modules\API\Authenticate\Service\AuthService $authService
     */
    protected \Modules\API\Authenticate\Service\AuthService $authService;


    /**
     * init
     *
     * Initialisation des objets en preDispatche
     *
     * @return void|Response
     */
    public function init()
    {
        $this->methode = $this->contenaire->get(\Psr\Http\Message\ServerRequestInterface::class)->getServerParams()['REQUEST_METHOD'];
        $this->post = $this->contenaire->get(\Psr\Http\Message\ServerRequestInterface::class)->getParsedBody();

        $this->authService = new \Modules\API\Authenticate\Service\AuthService(
            $this->pdo,
            $this->JWTKEY
        );

        if (!(new SecuriteIP($this->pdo, $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'], '', 'A'))
                ->IPValid()
        ) {
            $this->authService->setStatusCode(401);
        }

        if (!(
                array_key_exists('client_secret', $this->post)
                && array_key_exists('client_id', $this->post)
            ) || $this->authService->getStatusCode() !== 200
        ) {
            return new Response(
                $this->authService->getStatusCode(),
                [
                    'Content-Type' => 'application/json'
                ],
                (string)\json_encode(
                    ['Error' => $this->authService->getMessageStatusCode()]
                )
            );
        }
    }

    /**
     * getTokenAction
     *
     * @return Response
     */
    public function getTokenAction(): Response
    {
        $payload = $this->authService->generateToken(
            60 * 15,
            $this->post['client_id'],
            $this->post['client_secret'],
            'password'
        );

        return new Response($this->authService->getStatusCode(), [
            'Content-Type' => 'application/json'
        ], (string)\json_encode(
            $payload
        ));
    }
}
