<?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;

/**
 * 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) {
    $module_path = $this->moduleHandler()->getModule('automated_testing_kit')->getPath();
    $file_path = $module_path . '/data/' . $request->query->get('filename');
    $content_type = $request->query->get('content-type');

    // Check if the file exists.
    if (!file_exists($file_path)) {
      // Optionally log an error or return a 404 response.
      // Or another appropriate route.
      return $this->redirect('entity.node.canonical');
    }

    $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)
    );

    // You might want to set the Content-Type header based on the file type.
    // Example for a text file:
    if ($content_type) {
      $response->headers->set('Content-Type', $content_type);
    }

    return $response;
  }

}
