<?php

namespace Oney\ThreeByFour\Plugin\Sales\Model\Order;

use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Model\Order\CreditmemoRepository;
use Magento\Sales\Model\OrderRepository;
use Oney\ThreeByFour\Api\Payment\CancelInterface;

/**
 * Creditmemo Repository Plugin
 * 
 * Plugin for Magento creditmemo repository.
 * Handles payment cancellation when creditmemo is saved.
 * 
 * @package Oney\ThreeByFour\Plugin\Sales\Model\Order
 * @version 1.0.0
 * @author Oney
 * @since 1.0.0
 */
class CreditmemoRepositoryPlugin
{
    /**
     * Payment cancellation service
     * 
     * @var CancelInterface
     * @version 1.0.0
     */
    private $_cancelService;
    
    /**
     * Order repository instance
     * 
     * @var OrderRepository
     * @version 1.0.0
     */
    private $_orderRepository;

    /**
     * Constructor
     * 
     * @param CancelInterface $cancelService Payment cancellation service
     * @param OrderRepository $orderRepository Order repository
     * @version 1.0.0
     */
    public function __construct(
        CancelInterface $cancelService,
        OrderRepository $orderRepository
    ) {
        $this->_cancelService = $cancelService;
        $this->_orderRepository = $orderRepository;
    }

    /**
     * After save creditmemo
     * 
     * Handles payment cancellation after creditmemo is saved.
     * 
     * @param CreditmemoRepository $subject Creditmemo repository
     * @param CreditmemoInterface $result Saved creditmemo
     * @return void
     * @version 1.0.0
     */
    public function afterSave(CreditmemoRepository $subject, $result): void
    {
        $this->_cancelService
            ->setCancellationAmount($result->getGrandTotal())
            ->setCancellationReasonCode(0)
            ->cancel($this->_orderRepository->get($result->getOrderId()));
    }
}
