<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Handler;

use Paysera\CheckoutSdk\Exception\IntegrationException;
use Paysera\PrestashopPayments\Dto\CallbackResponse;
use Paysera\PrestashopPayments\Exception\CallbackException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

class CallbackResponseHandler
{
    private PaymentCallbackHandler $paymentCallbackHandler;
    private LoggerInterface $logger;

    public function __construct(
        PaymentCallbackHandler $paymentCallbackHandler,
        LoggerInterface $logger
    ) {
        $this->paymentCallbackHandler = $paymentCallbackHandler;
        $this->logger = $logger;
    }

    public function handleCallback(ServerRequestInterface $request): CallbackResponse
    {
        try {
            $this->paymentCallbackHandler->processCallback($request);

            return CallbackResponse::success();
        } catch (CallbackException $exception) {
            $this->logger->error('Callback processing failed', [
                'exception' => $exception->getMessage(),
                'code' => $exception->getHttpCode(),
                'retry' => $exception->shouldRetry(),
            ]);

            return CallbackResponse::error(
                $exception->getHttpCode(),
                $exception->getMessage()
            );
        } catch (IntegrationException $exception) {
            $this->logger->error('SDK integration error', [
                'exception' => $exception->getMessage(),
            ]);

            return CallbackResponse::error(401, 'Unauthorized');
        } catch (\Throwable $exception) {
            $this->logger->error('Unexpected callback error', [
                'exception' => $exception->getMessage(),
                'trace' => $exception->getTraceAsString(),
            ]);

            return CallbackResponse::error(500, 'Internal Server Error');
        }
    }
}
