<?php

namespace Formatrica\Capability\Rules;

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

use Formatrica\Capability\Capabilities;
use Formatrica\Capability\Premium_Config_Rule_Interface;
use Formatrica\Integrations\Integration_Usage_Snapshot;

/**
 * P-WH1: on Free, Zapier and Make are each limited to ONE form across the
 * whole install; Pro (integrations.webhook_unlimited) removes the cap.
 * Enforced at save: newly ENABLING the integration on a second form is
 * reverted with a rejection naming the form that holds the slot. A form where
 * it was already enabled is grandfathered (turning off is always allowed and
 * frees the slot). Counts ALL forms regardless of active state.
 */
final class Webhook_Unlimited_Rule implements Premium_Config_Rule_Interface
{
    public function __construct(private ?Integration_Usage_Snapshot $usage = null)
    {
        $this->usage = $usage ?? new Integration_Usage_Snapshot();
    }

    public function capability(): string
    {
        return Capabilities::INTEGRATIONS_WEBHOOK_UNLIMITED;
    }

    public function enforce(array &$config, array $existing): array
    {
        $rejected = [];

        // Form id injected by Form_Repository::save for cross-form context.
        $current_form_id = (int) ($existing['id'] ?? 0);

        foreach (['make', 'zapier'] as $integration) {
            $is_enabled = !empty($config['options']['integrations'][$integration]['enabled']);
            $was_enabled = !empty($existing['options']['integrations'][$integration]['enabled']);

            // Turning off, or already on without change → both fine.
            if (!$is_enabled || $was_enabled) {
                continue;
            }

            $other = $this->usage->first_other_form_using($integration, $current_form_id);
            if ($other === null) {
                continue; // slot is free
            }

            $config['options']['integrations'][$integration]['enabled'] = false;

            $rejected[] = [
                'key' => 'options.integrations.' . $integration . '.enabled',
                'reason' => sprintf(
                    /* translators: 1: integration name, 2: form title holding the slot */
                    __('The free edition allows %1$s on one form across the whole site. It is currently in use on “%2$s”. Disable it there to free up the slot, or upgrade to Pro for unlimited.', 'formatrica'),
                    ucfirst($integration),
                    $other['title']
                ),
                'capability' => $this->capability(),
                'feature' => 'webhook_unlimited',
                'other_form_id' => (string) $other['id'],
            ];
        }

        return $rejected;
    }
}
