<?php declare(strict_types=1);

namespace Shop\Presentation\Controllers;

use Core\Exceptions\ResponseException;
use Symfony\Component\HttpFoundation\Response;

trait ClientApiKeyTrait
{
    public function validateToken()
    {

        $ip = $this->request->server->get('REMOTE_ADDR');

        if(!$key = $this->request->headers->get('x-api-key')){
            $key = $this->request->cookies->get('x-api-key');
        }

        if (!$key) {
            if($this->logger) {
                $this->logger->error('X-API-KEY not found for client, ip: ', $this->request->headers->all());
            }
            throw new ResponseException(new Response('X-API-KEY not found for client, ip: ', Response::HTTP_FORBIDDEN));
        }

        if (getenv('TOKEN_API') !== $key) {
            if($this->logger) {
                $this->logger->error('x-api-key '.$key.' incorrect for client, ip: '. $ip, $this->request->headers->all());
            }
            throw new ResponseException(new Response('x-api-key '.$key.' incorrect for client, ip: '. $ip, Response::HTTP_FORBIDDEN));
        }
    }
}