<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * P-CRM2: gate NEW Salesforce setup behind integrations.crm_salesforce.
 * Identical pattern to Hubspot_Pro_Rule (grandfather existing-enabled, revert
 * only an active enable/credential attempt).
 */
final class Salesforce_Pro_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::INTEGRATIONS_CRM_SALESFORCE;
    }

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

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

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

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

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

        return [[
            'key' => 'options.integrations.salesforce',
            'reason' => __('The Salesforce integration is a Pro feature; the change was reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature' => 'crm_salesforce',
        ]];
    }
}
