<?php

namespace Velis\Mvc\Controller;

use Phalcon\Http\Message\ResponseStatusCodeInterface;
use Velis\Api\HttpExceptionHandler\HttpException;
use Velis\Lang;

trait ErrorHelpersTrait
{
    /**
     * Returns authorization error message
     * @throws HttpException
     */
    public function unauthorized(?string $message = null): void
    {
        $this->error(
            Lang::get('USER_AUTHORIZATION_FAILED') . ($message ? ' (' . $message . ')' : ''),
            ResponseStatusCodeInterface::STATUS_UNAUTHORIZED
        );
    }

    /**
     * Returns authorization error message
     * @throws HttpException
     */
    public function tokenExpired(): void
    {
        $this->notAcceptable('Authorization token expired');
    }

    /**
     * @throws HttpException
     */
    public function notAcceptable(?string $message = null): void
    {
        $this->error(
            $message ?? 'Not acceptable',
            ResponseStatusCodeInterface::STATUS_NOT_ACCEPTABLE
        );
    }

    /**
     * Returns access denied error message
     * @throws HttpException
     */
    public function deny(?string $message = null): void
    {
        $this->error(
            $message ?? 'Access denied',
            ResponseStatusCodeInterface::STATUS_FORBIDDEN
        );
    }

    /**
     * Returns method not implemented error message
     * @throws HttpException
     */
    public function methodNotAllowed(?string $message = null): void
    {
        $this->error(
            $message ?? 'Method not allowed',
            ResponseStatusCodeInterface::STATUS_METHOD_NOT_ALLOWED
        );
    }

    /**
     * Returns resource "not found" error message
     * @throws HttpException
     */
    public function notFoundAction(?string $message = null): void
    {
        $this->error(
            $message ?? 'Resource not found',
            ResponseStatusCodeInterface::STATUS_NOT_FOUND
        );
    }

    /**
     * Returns unsupported expected response format
     * @throws HttpException
     */
    public function unsupportedMediaType(?string $message = null): void
    {
        $this->error(
            $message ?? 'Only json mode available',
            ResponseStatusCodeInterface::STATUS_UNSUPPORTED_MEDIA_TYPE
        );
    }

    /**
     * Returns json formatted error message
     */
    public function error(
        ?string $msg = null,
        int $code = ResponseStatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR,
        ?array $details = null
    ): void {
        /**
         * We do not want this exception to be caught in the controller - we want to handle it in the ExceptionHandler.
         * So we do not raise it to the higher logic.
         * @noinspection PhpUnhandledExceptionInspection
         */
        throw new HttpException(message: $msg, details: $details, httpCode: $code);
    }
}
