<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes\ExceptionHandling;

use Exception;
use Psr\Log\LoggerInterface;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;
use Shopware\Plugins\ViisonCommon\Components\ExceptionTranslation\ExceptionTranslator;

/**
 * Trait that can be used in Backend Controllers to handle exceptions and send a correct error response to the client.
 */
trait BackendExceptionHandling
{
    /**
     * @param Exception $e
     * @throws Exception
     */
    private function handleException(Exception $e)
    {
        /** @var LoggerInterface $logger */
        $logger = $this->get('viison_common.logger');

        $logMessage = sprintf(
            'Backend action "%s/%s" failed with exception: %s',
            $this->Request()->getControllerName(),
            $this->Request()->getActionName(),
            $e->getMessage()
        );

        $logger->error(
            $logMessage,
            [
                'user' => ViisonCommonUtil::getCurrentUser() ? ViisonCommonUtil::getCurrentUser()->getName() : null,
                'exception' => ViisonCommonUtil::exceptionToArray($e),
            ]
        );

        if ($e instanceof \RuntimeException || $e instanceof \LogicException) {
            throw $e;
        }

        if ($this->container->getParameter('shopware.front.throwExceptions')) {
            throw $e;
        }

        /** @var ExceptionTranslator $exceptionTranslator */
        $exceptionTranslator = $this->get('viison_common.exception_translator');

        $this->View()->message = $exceptionTranslator->translate($e);
        $this->View()->success = false;

        if ($this->container->getParameter('shopware.front.showException')) {
            $this->View()->exception = ViisonCommonUtil::exceptionToArray($e);
        }
    }
}
