<?php

namespace Drupal\nodehive_public_api;

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;

/**
 * Provides consistent JSON response helpers for API controllers.
 *
 * Success envelope: { "status": "ok", "data": { ... } }
 * Error envelope:
 * { "status": "error", "error": { "code": 404, "message": "..." } }
 */
trait ApiResponseTrait {

  /**
   * Creates a successful cacheable JSON response with a standard envelope.
   *
   * @param array $data
   *   The response data.
   * @param \Drupal\Core\Cache\CacheableMetadata|null $cache_metadata
   *   Optional cache metadata.
   *
   * @return \Drupal\Core\Cache\CacheableJsonResponse
   *   The cacheable JSON response.
   */
  protected function apiSuccess(array $data, ?CacheableMetadata $cache_metadata = NULL): CacheableJsonResponse {
    $response = new CacheableJsonResponse([
      'status' => 'ok',
      'data' => $data,
    ]);

    if ($cache_metadata) {
      $response->addCacheableDependency($cache_metadata);
    }

    return $response;
  }

  /**
   * Creates an error cacheable JSON response with a standard envelope.
   *
   * @param string $message
   *   The error message.
   * @param int $http_status
   *   The HTTP status code.
   * @param \Drupal\Core\Cache\CacheableMetadata|null $cache_metadata
   *   Optional cache metadata. If NULL, a default with user.permissions
   *   context is added.
   *
   * @return \Drupal\Core\Cache\CacheableJsonResponse
   *   The cacheable JSON response.
   */
  protected function apiError(string $message, int $http_status = 500, ?CacheableMetadata $cache_metadata = NULL): CacheableJsonResponse {
    $response = new CacheableJsonResponse([
      'status' => 'error',
      'error' => [
        'code' => $http_status,
        'message' => $message,
      ],
    ], $http_status);

    if (!$cache_metadata) {
      $cache_metadata = new CacheableMetadata();
      $cache_metadata->addCacheContexts(['user.permissions']);
    }
    $response->addCacheableDependency($cache_metadata);

    return $response;
  }

}
