<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * P-SMS: gate NEW Twilio SMS setup behind integrations.sms_twilio. Previously
 * ACTIVE config is grandfathered at save (though the cost-bearing dispatcher
 * independently stops sending after grace, per the gated-side-effect policy);
 * a dormant block with an unused secret is NOT a grandfather candidate —
 * re-activating it on Free is still rejected.
 */
final class Twilio_Pro_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::INTEGRATIONS_SMS_TWILIO;
    }

    public function enforce(array &$config, array $existing): array
    {
        if (!isset($config['options']['integrations']['twilio']) || !is_array($config['options']['integrations']['twilio'])) {
            return [];
        }

        $incoming = &$config['options']['integrations']['twilio'];
        $stored = is_array($existing['options']['integrations']['twilio'] ?? null)
            ? $existing['options']['integrations']['twilio']
            : [];

        if (!empty($stored['enabled'])) {
            return [];
        }

        $user_activated = !empty($incoming['enabled']) || !empty($incoming['api_key_secret']);
        if (!$user_activated) {
            return [];
        }

        $incoming = $stored !== [] ? $stored : ['enabled' => false];

        return [[
            'key' => 'options.integrations.twilio',
            'reason' => __('Twilio SMS notifications are a Pro feature; the change was reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature' => 'sms_twilio',
        ]];
    }
}
