<?php

namespace Drupal\siteimprove_accessibility\Plugin\rest\resource;

use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\rest\Attribute\RestResource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ModifiedResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

#[RestResource(
  id: 'siteimprove_accessibility_alfa_scan_by_node_resource',
  label: new TranslatableMarkup('Alfa Scan by Node'),
  uri_paths: [
    'canonical' => '/siteimprove-accessibility/alfa-scan/node/{nid}',
  ],
)]
/**
 * Provides a REST method to fetch AlfaScan data by node ID.
 */
final class AlfaScanByNodeResource extends ResourceBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected AccountProxyInterface $currentUser;

  /**
   * DataFormatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected DateFormatterInterface $dateFormatter;

  /**
   * Constructs a new AlfaScanByNodeResource object.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    EntityTypeManagerInterface $entity_type_manager,
    AccountProxyInterface $current_user,
    DateFormatterInterface $date_formatter,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $current_user;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('siteimprove_accessibility'),
      $container->get('entity_type.manager'),
      $container->get('current_user'),
      $container->get('date.formatter')
    );
  }

  /**
   * Responds to GET requests to fetch AlfaScan data by Node ID.
   *
   * @param int $nid
   *   The Node ID for which to retrieve AlfaScan data.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   The response containing scan results.
   */
  public function get(int $nid): ModifiedResourceResponse {
    if (!$this->currentUser->hasPermission('run siteimprove_accessibility scan')) {
      throw new AccessDeniedHttpException('You do not have permission to access this resource.');
    }

    $alfa_scan_entities = $this->entityTypeManager
      ->getStorage('alfa_scan')
      ->loadByProperties(['nid' => $nid]);

    if (empty($alfa_scan_entities)) {
      // No scan was triggered for the node.
      $data = [
        'scan_results' => NULL,
      ];
    }
    else {
      $alfa_scan = reset($alfa_scan_entities);
      $changed = (int) $alfa_scan->get('changed')->value;

      $data = [
        'nid' => $nid,
        'scan_results' => json_decode($alfa_scan->get('scan_results')->value, TRUE),
        'timestamp' => $changed,
        'changed' => $this->dateFormatter->format($changed, 'custom', 'M d, Y'),
      ];
    }

    return new ModifiedResourceResponse($data, 200);
  }

}
