<?php

namespace Drupal\social_auth_vk\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;
use League\OAuth2\Client\Tool\ArrayAccessorTrait;

/**
 * Represents a VK user resource.
 */
class VkUser implements ResourceOwnerInterface {

  use ArrayAccessorTrait;

  /**
   * Data from API response.
   *
   * @var array
   */
  protected array $response;

  /**
   * Constructs object.
   *
   * @param array $response
   *   Data from API response.
   */
  public function __construct(array $response) {
    $this->response = $response;
  }

  /**
   * Gets resource owner attribute by key. The key supports dot notation.
   *
   * @param string $key
   *   Field key.
   *
   * @return mixed
   *   Value by key from response.
   */
  public function getAttribute(string $key): mixed {
    return $this->getValueByKey($this->response, (string) $key);
  }

  /**
   * Get user first name.
   *
   * @return string
   *   User first name.
   */
  public function getFirstName(): string {
    return $this->getAttribute('first_name');
  }

  /**
   * Get user last name.
   *
   * @return string
   *   User last name.
   */
  public function getLastName(): string {
    return $this->getAttribute('last_name');
  }

  /**
   * Get user user id.
   *
   * @return string
   *   User ID.
   */
  public function getId(): string {
    return $this->getAttribute('id');
  }

  /**
   * Get user image url.
   *
   * @return string|null
   *   Image URL.
   */
  public function getImageUrl(): ?string {
    return $this->getAttribute('photo_max_orig');
  }

  /**
   * Get user email, if available.
   *
   * @return string|null
   *   User email.
   */
  public function getEmail(): ?string {
    return $this->getAttribute('email');
  }

  /**
   * Return owner details available as an array.
   *
   * @return array
   *   Owner details.
   */
  public function toArray(): array {
    return $this->response;
  }

}
