<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * P-CRM1: gate NEW HubSpot setup behind integrations.crm_hubspot. Existing
 * enabled configs are grandfathered — they pass through unchanged and keep
 * dispatching on Free (the dispatcher stays capability-blind, in core). Only
 * a user actively trying to ENABLE HubSpot (or set a credential) on Free is
 * reverted; the sanitizer always materialises a full default block, so a naive
 * deep-compare would emit a spurious rejection on every save.
 */
final class Hubspot_Pro_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::INTEGRATIONS_CRM_HUBSPOT;
    }

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

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

        // Grandfathered: previously enabled keeps working on Free.
        if (!empty($stored['enabled'])) {
            return [];
        }

        // Only intervene on an active attempt to enable / set a credential.
        $user_activated = !empty($incoming['enabled']) || !empty($incoming['access_token']);
        if (!$user_activated) {
            return [];
        }

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

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