<?php

namespace Drupal\siteimprove_accessibility\Plugin\rest\resource;

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 Drupal\siteimprove_accessibility\Repository\OccurrenceRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

#[RestResource(
  id: 'siteimprove_accessibility_issues_resource',
  label: new TranslatableMarkup('Issues'),
  uri_paths: [
    'canonical' => '/siteimprove-accessibility/issues',
  ],
)]
/**
 * Provides a REST method to fetch issues.
 */
final class IssuesResource extends ResourceBase {

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

  /**
   * Occurrence repository service.
   *
   * @var \Drupal\siteimprove_accessibility\Repository\OccurrenceRepository
   */
  protected OccurrenceRepository $occurrenceRepository;

  /**
   * Constructs a new IssuesResource.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user,
    OccurrenceRepository $occurrence_repository,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->currentUser = $current_user;
    $this->occurrenceRepository = $occurrence_repository;
  }

  /**
   * {@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('current_user'),
      $container->get('siteimprove_accessibility.occurrence_repository'),
    );
  }

  /**
   * Responds to GET requests to fetch Issues data.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   The response containing scan results.
   */
  public function get(Request $request): ModifiedResourceResponse {
    if (!$this->currentUser->hasPermission('run siteimprove_accessibility scan')) {
      throw new AccessDeniedHttpException('You do not have permission to access this resource.');
    }

    $issues = $this->occurrenceRepository->findIssuesWithPages();

    return new ModifiedResourceResponse($issues, 200);
  }

}
