<?php
/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

namespace Resursbank\MerchantApi\Hook;

use Order;
use Resursbank\Ecom\Module\Payment\Enum\Status;
use Resursbank\Ecom\Module\Payment\Repository;
use Resursbank\MerchantApi\Repository\ResursbankOrder;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Service\Order as OrderService;
use Resursbank\MerchantApi\Traits\AdminOrderHook;
use Throwable;

/**
 * Handle order edit actions.
 */
class ActionOrderEdited
{
    use AdminOrderHook;

    /**
     * @param ResursbankOrder $orderRepository
     */
    public function __construct(
        private readonly ResursbankOrder $orderRepository
    ) {
    }

    /**
     * Updates Resurs Bank payment.
     *
     * @param array $parameters
     * @return void
     */
    public function exec(array $parameters): void
    {
        try {
            /** @var Order $order */
            $order = $parameters['order'];
            $mapiPayment = $this->getMapiPayment(
                orderId: $order->id,
                repository: $this->orderRepository
            );

            if ($mapiPayment->status === Status::TASK_REDIRECTION_REQUIRED ||
                !OrderService::modificationPossible(
                    payment: $mapiPayment,
                    order: $order
                ) ||
                !$mapiPayment->canCancel()
            ) {
                return;
            }

            Repository::cancel(paymentId: $mapiPayment->id);

            $products = $order->getProducts();
            $orderLines = OrderService::convert(
                order: $order
            );

            if (count($products) > 0) {
                Repository::addOrderLines(
                    paymentId: $mapiPayment->id,
                    orderLines: $orderLines
                );
            }
        } catch (Throwable $error) {
            Log::error(message: $error);
            // @todo: Add warning about failed update
        }
    }
}
