<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\api\Core;

use Drupal\languagewire_translation_provider\api\Core\Exception\Error;
use Drupal\languagewire_translation_provider\api\Endpoints\Authentication;

/**
 * Connection authenticator.
 */
final class Authenticator {
  /**
   * Client ID.
   *
   * @var string
   */
  private string $clientID;

  /**
   * Client Secret.
   *
   * @var string
   */
  private string $clientSecret;

  public function __construct(string $clientID, string $clientSecret) {
    $this->clientID = $clientID;
    $this->clientSecret = $clientSecret;
  }

  /**
   * Authenticate.
   *
   * @return string
   *   Access token
   *
   * @throws \Drupal\languagewire_translation_provider\api\Core\Exception\Error
   */
  public function authenticate(): string {
    $authenticate = new Authentication(new Settings('new', 'authentication'));
    $authenticate->setCredentials($this->clientID, $this->clientSecret);

    $resultAuthentication = $authenticate->execute();

    if ($resultAuthentication === NULL) {
      throw new Error($authenticate->getErrorMessage());
    }

    return $resultAuthentication['access_token'];
  }

}
