<?php

namespace Drupal\disign_slide_api\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Provides methods for handling API requests related to slide set changes.
 */
class ApiController extends ControllerBase {

  /**
   * Computes the most recent change date for the given node or its descendants.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node object used to compute or retrieve the slide set change.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response containing the change date as a UNIX timestamp.
   */
  public function getSlideSetChange(NodeInterface $node): JsonResponse {
    if ($node->bundle() !== 'slide_set') {
      return new JsonResponse(['error' => 'Not a slide set'], 400);
    }

    return new JsonResponse(['changed' => $this->doGetSlideSetChange($node)]);
  }

  /**
   * Recursively retrieves the most recent "changed" timestamp for a slide set.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node object to evaluate, which may contain references to other slides
   *   or slide sets.
   *
   * @return int
   *   The latest "changed" timestamp found among the node and its referenced
   *   slides or slide sets.
   */
  private function doGetSlideSetChange(NodeInterface $node): int {
    $changed = (int) $node->get('changed')->value;
    foreach ($node->get('field_contentref')->referencedEntities() as $slide) {
      if ($slide->bundle() === 'slide_set') {
        $slideChange = $this->doGetSlideSetChange($slide);
      }
      else {
        $slideChange = (int) $slide->get('changed')->value;
        $this->moduleHandler()->alter('disign_slide_api_slide_change', $slideChange, $slide);
      }
      $changed = max($changed, $slideChange);
    }
    return $changed;
  }

}
