<?php declare(strict_types=1);
/**
 * @author Ryan Spaeth <rspaeth@spaethtech.com>
 * @copyright 2025 - Spaeth Technologies, Archous Networks
 */

namespace SpaethTech\UCRM\SDK\Controllers;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Twig;
use SpaethTech\UCRM\SDK\Plugin;

abstract class BaseController
{
  public function __construct(
    protected readonly Plugin $plugin,
    protected readonly Client $client,
    protected readonly Twig $twig
  ) {
    $this->validateDependencies();
  }

  protected function validateDependencies(): void
  {
    if (!$this->plugin) {
      throw new \InvalidArgumentException("Plugin dependency is required");
    }

    if (!$this->client) {
      throw new \InvalidArgumentException("Client dependency is required");
    }

    if (!$this->twig) {
      throw new \InvalidArgumentException("Twig dependency is required");
    }
  }

  protected function json(
    Response $response,
    array|string $data,
    int $code = 200
  ): Response {
    // If string is provided, wrap it in a message object
    if (is_string($data)) {
      $data = [
        ($code >= 400) ? "error" : "message" => $data,
        "code" => $code
      ];
    }

    if (!isset($data["code"])) {
      $data["code"] = $code;
    }

    $json = json_encode($data);
    if ($json === false) {
      $json = '{"error":"JSON encoding failed","code":500}';
      $code = 500;
    }

    $response->getBody()->write($json);
    return $response
      ->withHeader("Content-Type", "application/json")
      ->withStatus($code);
  }
}