<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\ffmpeg_media\Service\ProgressTrackerInterface;
use Drupal\ffmpeg_media\Trait\ErrorRedactionTrait;
use Drupal\media\MediaInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller for progress API endpoints.
 */
final class ProgressController extends ControllerBase {

  use ErrorRedactionTrait;

  /**
   * Constructs a ProgressController object.
   *
   * @param \Drupal\ffmpeg_media\Service\ProgressTrackerInterface $progressTracker
   *   Progress tracker service.
   * @param \Drupal\Core\Session\AccountProxyInterface|null $accountProxy
   *   Current user account proxy.
   */
  public function __construct(
    #[Autowire(service: ProgressTrackerInterface::class)]
    protected readonly ProgressTrackerInterface $progressTracker,
    #[Autowire(service: 'current_user')]
    protected readonly ?AccountProxyInterface $accountProxy = NULL,
  ) {}

  /**
   * {@inheritdoc}
   */
  #[\Override]
  protected function getErrorRedactionAccount(): ?AccountInterface {
    return $this->accountProxy;
  }

  /**
   * Gets progress for a media entity.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The media entity.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   JSON response with progress data.
   */
  public function getProgress(MediaInterface $media, Request $request): JsonResponse {
    if (!$media->access('view')) {
      return new JsonResponse([
        'status' => 'forbidden',
        'message' => 'Access denied for this media.',
      ], 403, ['Cache-Control' => 'no-cache, no-store, must-revalidate']);
    }

    $mediaId = (int) $media->id();
    $fieldName = (string) $request->query->get('field_name', '');
    $progress = $this->progressTracker->getProgress($mediaId, $fieldName);

    if ($progress === NULL) {
      return new JsonResponse([
        'status' => 'unknown',
        'message' => 'No conversion in progress for this media.',
      ], 404, ['Cache-Control' => 'no-cache, no-store, must-revalidate']);
    }

    $responseData = $progress->toArray();
    if ($this->shouldRedactError($progress, $responseData['error'] ?? NULL)) {
      $responseData['error'] = self::SAFE_ERROR_MESSAGE;
    }

    return new JsonResponse($responseData, 200, ['Cache-Control' => 'no-cache, no-store, must-revalidate']);
  }

}
