<?php

namespace Components\Support;

use Components\Models\NewsletterItem;
use Components\Models\Audience;
use Components\Support\Htmx;

/**
 * FlowCache helper to invalidate flow caches for different module types.
 */
class FlowCache
{
    /**
     * Invalidate the flow cache for a given type and ID.
     *
     * @param string $type The type: 'newsletter_item', 'audience', or a module key.
     * @param int|string $id The ID of the item or audience (0 for generic module).
     * @param array $options Optional settings:
     *                      - 'event_prefix': if provided, triggers HTMX refresh event.
     *                      - 'flush': if true, flushes HTMX triggers immediately.
     */
    public static function invalidate(string $type, $id = 0, array $options = []): void
    {
        $id = (int)$id;
        $eventPrefix = (string)($options['event_prefix'] ?? $type);

        try {
            if ($type === 'newsletter_item' && $id > 0) {
                NewsletterItem::invalidateFlowCacheById($id);
                Htmx::trigger($eventPrefix . ':expandable:refresh', ['id' => (string)$id]);
            } elseif ($type === 'audience' && $id > 0) {
                $model = Audience::find($id);
                if ($model) {
                    // Also invalidate the cached result_count so list counters refresh correctly
                    try { $model->invalidateResultCountCache(true); } catch (\Throwable $e) { /* ignore */ }
                }

                FlowHtmlCache::invalidateOwner(FlowHtmlCache::OWNER_AUDIENCE, $id);

                // Trigger refresh of the expandable flow AND all count anchors
                Htmx::trigger($eventPrefix . ':expandable:refresh', ['id' => (string)$id]);
                Htmx::trigger($eventPrefix . ':counts:refresh', ['id' => (string)$id, 'ts' => (string) time()]);
            } elseif ($type !== '' && $type !== 'newsletter_item' && $type !== 'audience') {
                $moduleKey = $type;
                FlowHtmlCache::invalidateOwner(FlowHtmlCache::OWNER_MODULE, $moduleKey);
                // For trigger modules, the ID might be 0, but the event prefix is often the module key
                Htmx::trigger($eventPrefix . ':expandable:refresh', ['id' => (string)$id]);
            }
        } catch (\Throwable $e) {
            // ignore
        }

        if (!empty($options['flush'])) {
            try { Htmx::flushTriggers(); } catch (\Throwable $e) { /* ignore */ }
        }
    }
}
