<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_category\Controller\Api;

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\flowdrop\Controller\Api\ApiResponseTrait;
use Drupal\flowdrop_node_category\FlowDropNodeCategoryInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller for category API endpoints.
 *
 * Provides category metadata (label, icon, color, description) for the
 * FlowDrop workflow editor sidebar.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class CategoriesController extends ControllerBase {

  use ApiResponseTrait;

  /**
   * Get all categories.
   *
   * @return \Drupal\Core\Cache\CacheableJsonResponse
   *   JSON response with all category definitions.
   */
  public function getCategories(): CacheableJsonResponse {
    $cacheMetadata = new CacheableMetadata();
    $cacheMetadata->addCacheContexts([
      'user.permissions',
      'languages:language_interface',
    ]);
    $cacheMetadata->addCacheTags(['config:flowdrop_node_category_list']);

    try {
      $storage = $this->entityTypeManager()->getStorage('flowdrop_node_category');
      $entities = $storage->loadMultiple();

      $categories = [];
      foreach ($entities as $entity) {
        if ($entity instanceof FlowDropNodeCategoryInterface && $entity->status()) {
          $cacheMetadata->addCacheableDependency($entity);

          $categories[] = [
            'name' => $entity->id(),
            'label' => $entity->label(),
            'icon' => $entity->getIcon(),
            'color' => $entity->getColor(),
            'description' => $entity->getDescription(),
          ];
        }
      }

      return $this->cacheableSuccessResponse($categories, $cacheMetadata);
    }
    catch (\Exception $e) {
      return $this->cacheableErrorResponse($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR, $cacheMetadata);
    }
  }

}
