<?php

namespace Formatrica\Capability\Rules;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Formatrica\Capability\Capabilities;
use Formatrica\Capability\Premium_Config_Rule_Interface;

/**
 * Save-path gate for headless API submissions (Pro api.headless). Reverts an
 * attempt to ENABLE the per-form toggle on Free; an already-enabled stored
 * value is preserved across a lapse (grandfathered config — though the runtime
 * Headless_Auth_Stage independently stops accepting API calls without the
 * capability, per the gated-side-effect policy).
 */
final class Headless_Submission_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::API_HEADLESS;
    }

    public function enforce(array &$config, array $existing): array
    {
        $incoming = !empty($config['options']['headless_submission_enabled']);
        $stored = !empty($existing['options']['headless_submission_enabled']);

        // Only intervene when the incoming payload turns the toggle ON and the
        // stored value was off — preserves existing Pro-authored true values.
        if ($incoming && !$stored) {
            $config['options']['headless_submission_enabled'] = false;
            return [[
                'key' => 'options.headless_submission_enabled',
                'reason' => __('Anonymous API submission is a Pro feature; reverted to off.', 'formatrica'),
                'capability' => $this->capability(),
                'feature' => 'headless_submissions',
            ]];
        }

        return [];
    }
}
