<?php
/**
 * BookiFlex Payment Extension
 *
 * @package    BookiFlex
 * @subpackage Payment
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

 namespace BookiFlex\Extensions\Payment\Service;

use Payum\Core\Extension\Context;
use Payum\Core\Extension\ExtensionInterface;
use Payum\Core\Request\Generic;
use Payum\Core\Request\Notify;

defined( 'ABSPATH' ) || exit;

class SyncPaymentStatusExtension implements ExtensionInterface
{
    public function __construct(
        private readonly SyncPaymentStatusWithGateway $syncPaymentStatusWithGateway,
    ) {
    }

    /**
     * {@inheritDoc}
     */
    public function onPostExecute(Context $context): void
    {
        $request = $context->getRequest();
        if (! $request instanceof Generic) {
            return;
        }

        if (! $request instanceof Notify) {
            return;
        }

        if ($request->getToken() === null) {
            return;
        }

        // check the status and act accordingly
        $this->syncPaymentStatusWithGateway->sync($context->getGateway(), $request->getToken());
    }

    /**
     * {@inheritDoc}
     */
    public function onPreExecute(Context $context)
    {
    }

    /**
     * {@inheritDoc}
     */
    public function onExecute(Context $context)
    {
    }
}
