<?php

namespace Autogedal\TbiBank\Plugin;

use Autogedal\TbiBank\Model\PaymentMethod;
use Eadesigndev\Awb\Model\ResourceModel\Awb;
use Magento\Framework\Model\AbstractModel;
use Magento\Sales\Api\OrderRepositoryInterface;

/** Courier collection is always zero for TBI. AwbApprovalGate separately controls permission to generate an AWB. */
class AwbNoCod
{
    public function __construct(private OrderRepositoryInterface $orderRepository)
    {
    }

    public function beforeSave(Awb $subject, AbstractModel $awb): array
    {
        $this->clearCod($awb);
        return [$awb];
    }

    public function afterLoad(Awb $subject, $result, AbstractModel $awb, $value, $field = null)
    {
        // Old AWBs and retries must be corrected before a courier reads their payload.
        $this->clearCod($awb);
        return $result;
    }

    private function clearCod(AbstractModel $awb): void
    {
        $orderId = (int) $awb->getData('order_id');
        if ($orderId > 0) {
            // An order lookup failure must stop saving; never guess COD for an unknown order.
            $order = $this->orderRepository->get($orderId);
            if ($order->getPayment() && $order->getPayment()->getMethod() === PaymentMethod::CODE) {
                $awb->setData('repayment_value', 0.0);
            }
        }
    }
}
