<?php
declare(strict_types=1);

namespace Ekesto\CacheInvalidator\Taxonomy;

use Ekesto\CacheInvalidator\ArchiveDefaultsProvider;
use Ekesto\CacheInvalidator\InvalidatorRuntime;

/**
 * Centralized policy for taxonomy participation in invalidation flows.
 *
 * Note:
 * This policy is enforced at trigger time. Async jobs created before
 * a configuration change may still execute and are not re-evaluated.
 */
final class TaxonomyPolicy
{
    /**
     * Returns whether a taxonomy is enabled for a configured post type.
     *
     * @param string $postType Post type slug.
     * @param string $taxonomy Taxonomy slug.
     * @return bool
     */
    public static function isTaxonomyEnabledForPostType(string $postType, string $taxonomy): bool
    {
        $postType = sanitize_key($postType);
        $taxonomy = sanitize_key($taxonomy);

        if ($postType === '' || $taxonomy === '') {
            return false;
        }

        if ($taxonomy !== 'post_tag') {
            return true;
        }

        $config = InvalidatorRuntime::settingsRepository()->getPostTypeConfig($postType);
        if (!is_array($config)) {
            return false;
        }

        return !empty($config['tags_enabled']);
    }

    /**
     * Filters taxonomies allowed for archive resolution for a post type.
     *
     * Applies ArchiveDefaultsProvider restrictions first, then post_tag policy.
     *
     * @param string              $postType Post type slug.
     * @param array<string,mixed> $taxonomies Taxonomy map keyed by slug.
     * @return array<string,mixed>
     */
    public static function filterAllowedTaxonomies(string $postType, array $taxonomies): array
    {
        $postType = sanitize_key($postType);
        if ($postType === '') {
            return [];
        }

        $filtered = $taxonomies;

        $allowedTaxonomies = ArchiveDefaultsProvider::getAllowedTaxonomiesForPostType($postType);
        if (is_array($allowedTaxonomies)) {
            $allowedLookup = array_fill_keys(array_values(array_filter(array_map(
                static fn($taxonomy): string => sanitize_key((string) $taxonomy),
                $allowedTaxonomies
            ))), true);

            foreach (array_keys($filtered) as $taxonomyKey) {
                $taxonomy = sanitize_key((string) $taxonomyKey);
                if ($taxonomy === '' || !isset($allowedLookup[$taxonomy])) {
                    unset($filtered[$taxonomyKey]);
                }
            }
        }

        if (!self::isTaxonomyEnabledForPostType($postType, 'post_tag')) {
            unset($filtered['post_tag']);
        }

        return $filtered;
    }
}
