<?php

namespace idoit\Module\Forms\Proxy;

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use isys_component_session;
use isys_tenantsettings;
use Psr\Http\Message\ResponseInterface;

class RequestProxy
{
  private const JWT_SESSION_KEY = 'forms-jwt';

  private $apikey = '';

  private $apiname = '';

  private $jwtToken = null;

  /**
   * @var isys_component_session
   */
  private $session;

  private $url = '';

  public function authorize(): string
  {
    if (!is_string($this->jwtToken)) {
      $uid = $this->session->get_user_id();
      $client = new Client();
      $rq = $client->post($this->url . '/login', [
        'body' => json_encode([
          'apikey' => $this->apikey,
          'name' => $this->apiname,
        ]),
        RequestOptions::HEADERS => [
          'Content-Type' => 'application/json',
        ],
        RequestOptions::CONNECT_TIMEOUT => 2
      ]);
      $data = json_decode($rq->getBody()->getContents(), true);

      if (!is_array($data) || !isset($data['access_token'])) {
        throw new \Exception('Unauthorised');
      }

      $this->jwtToken = $data['access_token'];
    }

    return $this->jwtToken;
  }

  /**
   * @param string      $method
   * @param string      $url
   * @param string|null $body
   *
   * @return ResponseInterface
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function proxy(string $method, string $url, ?string $body = null): ResponseInterface
  {
    $token = $this->authorize();

    $client = new Client();

    return $client->request($method, $this->url . '/api/' . $url, [
      RequestOptions::BODY    => $body,
      RequestOptions::HEADERS => [
        'Content-Type' => 'application/json',
        'Authorization' => "bearer $token",
        RequestOptions::CONNECT_TIMEOUT => 2
      ]
    ]);
  }

  /**
   * RequestProxy constructor.
   *
   * @param isys_component_session $session
   */
  public function __construct(isys_component_session $session)
  {
    $this->session = $session;
    $this->url = isys_tenantsettings::get('forms.backend.api.url', 'http://127.0.0.1:3000');
    $this->apikey = isys_tenantsettings::get('forms.backend.api.apikey');
    $this->apiname = isys_tenantsettings::get('forms.backend.api.apiname');
  }
}
