<?php

namespace Drupal\automated_testing_kit\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
// For 403.
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Controller for serving the custom file.
 */
class TestDataController extends ControllerBase {

  /**
   * Serves the custom file.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
   *   The file as a binary file response.
   */
  public function serveFile(Request $request, string $filename) {
    $module_path = $this->moduleHandler()->getModule('automated_testing_kit')->getPath();
    $data_path = $module_path . '/data/';
    $file_path = realpath($data_path . $filename);

    // Check if the file exists.
    if ((!(bool) $file_path) || !str_starts_with($file_path, realpath($data_path))) {
      // Optionally log an error or return a 404 response.
      // Or another appropriate route.
      $this->getLogger('automated_testing_kit')->warning('Attempted to access @filename located at @file_path',
          ['@filename' => $filename, '@file_path' => $file_path]);
      throw new AccessDeniedHttpException('Access denied.');
    }

    // Determine the MIME type of the file. This is crucial for the browser.
    $mime_type = \Drupal::service('file.mime_type.guesser')->guessMimeType($file_path);
    if (!$mime_type) {
      // Fallback if MIME type cannot be guessed, or if it's a type you don't want to serve.
      $mime_type = 'application/octet-stream';
    }

    $response = new BinaryFileResponse($file_path);

    // Set appropriate headers for the file (optional, but recommended).
    $response->setContentDisposition(
    // Or DISPOSITION_ATTACHMENT for download.
        ResponseHeaderBag::DISPOSITION_INLINE,
        basename($file_path)
    );
    $response->headers->set('Content-Type', $mime_type);

    return $response;
  }

}
