<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Controller;

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\simple_interactive_maps\MapDataLoader;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Simple Interactive Maps routes.
 */
final class MapDataController extends ControllerBase {

  /**
   * Constructs a new MapDataController object.
   *
   * @param \Drupal\simple_interactive_maps\MapDataLoader $mapDataLoader
   *   The map data loader.
   */
  public function __construct(protected MapDataLoader $mapDataLoader) {}

  /**
   * {@inheritDoc}
   */
  public static function create(ContainerInterface $container): self {
    return new static(
      $container->get('simple_interactive_maps.map_data_loader')
    );
  }

  /**
   * Builds the response.
   */
  public function __invoke(): CacheableJsonResponse {
    try {
      $data = $this->mapDataLoader->loadMapData();
      $response = new CacheableJsonResponse();
      $response->setData($data);
    }
    catch (\Exception $e) {
      return new CacheableJsonResponse(['error' => 'An error occurred while loading the map data.'], 500);
    }

    $response->setmaxAge(3600);
    $response->setPublic();
    $response->setStatusCode(200);

    return $response;
  }

}
