<?php

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

namespace Resursbank\MerchantApi\Hook;

use PrestaShop\PrestaShop\Core\Action\ActionsBarButton;
use PrestaShop\PrestaShop\Core\Action\ActionsBarButtonsCollection;
use PrestaShop\PrestaShop\Core\Exception\TypeException;
use Resursbank\Ecom\Lib\Model\Payment;
use Resursbank\MerchantApi\Config\Config;
use Resursbank\MerchantApi\Repository\ResursbankOrder;
use Resursbank\MerchantApi\Traits\AdminOrderHook;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Util\Translator;
use Resursbank\MerchantApi\Service\Order as OrderService;
use Throwable;
use Resursbank\MerchantApi\Exception\InvalidArgumentException;
use PrestaShopBundle\Service\Routing\Router;

/**
 * Add custom action buttons to order view.
 */
class ActionGetAdminOrderButtons
{
    use AdminOrderHook;

    /**
     * @param Router $router
     * @param ResursbankOrder $repository
     * @param Config $config
     */
    public function __construct(
        private readonly Router $router,
        private readonly ResursbankOrder $repository,
        private readonly Config $config
    ) {
    }

    /**
     * Add buttons to order view.
     *
     * @param array $parameters
     * @return void
     */
    public function exec(array $parameters): void
    {
        try {
            if (!isset($parameters['actions_bar_buttons_collection'])) {
                throw new InvalidArgumentException(
                    message: 'Missing actions bar buttons collection'
                );
            }

            /** @var ActionsBarButtonsCollection $bar */
            $bar = $parameters['actions_bar_buttons_collection'];

            /** @var  $payment */
            $payment = $this->getMapiPayment(
                orderId: $this->getOrderId(parameters: $parameters),
                repository: $this->repository
            );

            $orderReference = $payment->order->orderReference;
            $isResursbank = OrderService::isResursbank(
                orderReference: $orderReference
            );

            if ($this->config->isAftershopEnabled() && $isResursbank) {
                if ($payment->canCapture()) {
                    self::addAftershopActionButton(
                        bar: $bar,
                        payment: $payment,
                        action: 'capture'
                    );
                }

                if ($payment->canCancel()) {
                    self::addAftershopActionButton(
                        bar: $bar,
                        payment: $payment,
                        action: 'cancel'
                    );
                }

                if ($payment->canRefund()) {
                    self::addAftershopActionButton(
                        bar: $bar,
                        payment: $payment,
                        action: 'refund'
                    );
                }
            }
        } catch (Throwable $error) {
            // @todo Add a flash message in frontend?
            Log::error(message: $error);
        }
    }

    /**
     * Add button to capture payment.
     *
     * @param ActionsBarButtonsCollection $bar
     * @param Payment $payment
     * @param string $action
     * @return void
     * @throws TypeException
     */
    private function addAftershopActionButton(
        ActionsBarButtonsCollection $bar,
        Payment $payment,
        string $action
    ): void {
        $url = $this->router->generate(
            name: 'resursbank_admin_order_' . $action,
            parameters: [
            'payment_id' => $payment->id
            ]
        );

        $bar->add(
            element: new ActionsBarButton(
                class: 'btn-secondary',
                properties: [
                    'id' => 'rb-' . $action . '-button',
                    'onclick' => "window.location.href='$url'"
                ],
                content: Translator::translate(phraseId: $action)
            )
        );
    }
}
