<?php

namespace Autogedal\TbiBank\Plugin;

use Autogedal\TbiBank\Model\PaymentMethod;
use Autogedal\TbiBank\Model\ApprovalAccounting;
use Autogedal\TbiBank\Model\ApprovalConfig;
use Eadesigndev\Awb\Model\AwbRepository;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Model\ResourceModel\Order as OrderResource;

/** Approval eligibility is independent of the no-COD rule. Check immediately before the courier call. */
class AwbApprovalGate
{
    public function __construct(
        private ApprovalConfig $config,
        private AwbRepository $awbRepository,
        private OrderFactory $orderFactory,
        private OrderResource $orderResource
    ) {
    }

    public function beforeGenerateAwb($subject, $awbId): array
    {
        $awb = $this->awbRepository->getById($awbId);
        $orderId = (int) $awb->getData('order_id');
        if ($orderId <= 0) {
            throw new LocalizedException(__('The AWB has no linked order.'));
        }
        // Fresh load: do not trust an order cached before approval/cancellation in this request.
        $order = $this->orderFactory->create();
        $this->orderResource->load($order, $orderId);
        if (!$order->getId()) {
            throw new LocalizedException(__('The AWB order could not be loaded.'));
        }
        if ($order->getPayment() && $order->getPayment()->getMethod() === PaymentMethod::CODE) {
            if (in_array($order->getState(), [Order::STATE_CANCELED, Order::STATE_CLOSED, Order::STATE_HOLDED], true)) {
                throw new LocalizedException(__('The TBI order cannot be shipped in its current state.'));
            }
            if ($this->config->isRequired($order->getStoreId())
                && !$order->getPayment()->getAdditionalInformation(ApprovalAccounting::MARKER)
            ) {
                throw new LocalizedException(__('AWB generation is blocked until TBI financing is approved.'));
            }
        }
        return [$awbId];
    }
}
