<?php

namespace Drupal\siteimprove_accessibility\Plugin\rest\resource;

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

#[RestResource(
  id: 'siteimprove_accessibility_daily_stats_resource',
  label: new TranslatableMarkup('Daily Stats'),
  uri_paths: [
    'canonical' => '/siteimprove-accessibility/daily-stats',
  ],
)]
/**
 * Provides a REST method to fetch Daily Stats.
 */
final class DailyStatsResource 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;

  /**
   * DailyStats repository service.
   *
   * @var \Drupal\siteimprove_accessibility\Repository\DailyStatsRepository
   */
  protected DailyStatsRepository $dailyStatsRepository;

  /**
   * DailyStats processor service.
   *
   * @var \Drupal\siteimprove_accessibility\DailyStatsProcessor
   */
  protected DailyStatsProcessor $dailyStatsProcessor;

  /**
   * Time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected TimeInterface $time;

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

  /**
   * Constructs a new DailyStatsResource.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    EntityTypeManagerInterface $entity_type_manager,
    AccountProxyInterface $current_user,
    DailyStatsRepository $daily_stats_repository,
    DailyStatsProcessor $daily_stats_processor,
    TimeInterface $time,
    DateFormatterInterface $date_formatter,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $current_user;
    $this->dailyStatsRepository = $daily_stats_repository;
    $this->dailyStatsProcessor = $daily_stats_processor;
    $this->time = $time;
    $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('siteimprove_accessibility.daily_stats_repository'),
      $container->get('siteimprove_accessibility.daily_stats_processor'),
      $container->get('datetime.time'),
      $container->get('date.formatter'),
    );
  }

  /**
   * Responds to GET requests to fetch DailyStats aggregated 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.');
    }
    // Fetch historical daily stats.
    $results = $this->dailyStatsRepository->findDailyStats();
    $daily_stats = $this->dailyStatsProcessor->prepareDailyStats($results);

    // Get today's timestamp at midnight.
    $todayTimestamp = strtotime('midnight', $this->time->getRequestTime());
    $todayFormatted = $this->dateFormatter->format($todayTimestamp, 'custom', 'Y-m-d');

    // Fetch today's real-time scan stats.
    $aggregatedStats = $this->dailyStatsProcessor->getAggregatedIssues();
    $todayStat = $this->dailyStatsProcessor->prepareStatRecord($aggregatedStats, $todayTimestamp);

    // Check if today’s date is already in the results.
    $lastIndex = count($daily_stats->issues) - 1;
    if ($lastIndex >= 0 && $daily_stats->issues[$lastIndex]['date'] === $todayFormatted) {
      // Replace existing placeholder with real-time data.
      $daily_stats->issues[$lastIndex] = $todayStat[0];
      $daily_stats->occurrences[$lastIndex] = $todayStat[1];
    }
    else {
      // Otherwise, append today's real-time data.
      $daily_stats->issues[] = $todayStat[0];
      $daily_stats->occurrences[] = $todayStat[1];
    }

    return new ModifiedResourceResponse([
      'issues' => $daily_stats?->issues,
      'occurrences' => $daily_stats?->occurrences,
    ], 200);
  }

}
