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


declare(strict_types=1);
namespace BookiFlex\Extensions\StripePayment\Action;

use ArrayAccess;
use ArrayObject;
use BookiFlex\Extensions\StripePayment\Action\CaptureAction;
use LogicException;
use Payum\Core\Request\Authorize;
use Payum\Core\Request\Generic;
use Payum\Core\Security\TokenInterface;
use Stripe\PaymentIntent;

defined( 'ABSPATH' ) || exit;

/**
 * Use for inheritance from CaptureAction
 */
final class AuthorizeAction extends CaptureAction
{
    public function embedNotifyTokenHash(ArrayObject $model, Generic $request): TokenInterface
    {
        $modeDataKey = $this->detectModeData($model);
        if ('payment_intent_data' !== $modeDataKey) {
            throw new LogicException('Authorize is reserved to `mode`=`payment` !');
        }

        return parent::embedNotifyTokenHash($model, $request);
    }

    public function embedOnModeData(ArrayObject $model, TokenInterface $token, string $modeDataKey): void
    {
        parent::embedOnModeData($model, $token, $modeDataKey);

        /** @var array $embeddedModeData */
        $embeddedModeData                   = $model->offsetGet($modeDataKey);
        $embeddedModeData['capture_method'] = PaymentIntent::CAPTURE_METHOD_MANUAL;
        $model->offsetSet($modeDataKey, $embeddedModeData);
    }

    public function supports($request): bool
    {
        if (false === $request instanceof Authorize) {
            return false;
        }

        return $request->getModel() instanceof ArrayAccess;
    }
}
