<?php declare(strict_types=1);

namespace Newland\NeosCommon\Controller;

use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Utility\Now;
use function Safe\json_encode;

abstract class AbstractApiController extends ActionController
{
    /** @var string */
    protected $mimeType = 'application/json';

    /** @var float|null */
    protected $browserCacheLifetimeHours = null;

    public function initializeAction()
    {
        parent::initializeAction();
        $this->response->setContentType($this->mimeType);

        if ($this->browserCacheLifetimeHours) {
            $this->response->setHeader('Cache-Control', 'max-age=' . ($this->browserCacheLifetimeHours * 60 * 60));
            $interval = sprintf('PT%dH', $this->browserCacheLifetimeHours);
            $this->response->setExpires(
                (new Now())->add(new \DateInterval($interval))->format(DATE_RFC822)
            );
        }
    }

    protected function callActionMethod(): void
    {
        try {
            parent::callActionMethod();
        } catch (\Throwable $e) {
            $this->handleError($e);
        }
    }

    protected function handleError(\Throwable $throwable): void
    {
        if ($throwable instanceof HttpException) {
            $this->response->setStatusCode($throwable->getCode());
        } else {
            $this->response->setStatusCode(500);
        }
        $this->response->setContent(
            json_encode(
                [
                    'error' => [
                        'code' => $throwable->getCode(),
                        'file' => $throwable->getFile(),
                        'line' => $throwable->getLine(),
                        'message' => $throwable->getMessage(),
                        'trace' => $throwable->getTrace(),
                    ],
                ]
            )
        );
    }
}
