<?php

namespace NewsletterBridge\Services\Query;

/**
 * Riferimento univoco a un termine: taxonomy:slug (es. category:tech, post_tag:offerte).
 */
class TaxonomyTermReference {

    public const SEPARATOR = ':';

    public static function encode(string $taxonomy, string $slug): string {
        return sanitize_key($taxonomy) . self::SEPARATOR . sanitize_title($slug);
    }

    /**
     * @return array{taxonomy: string, slug: string}|null
     */
    public static function parse(string $reference): ?array {
        $reference = trim($reference);
        if ($reference === '') {
            return null;
        }

        if (str_contains($reference, self::SEPARATOR)) {
            [$taxonomy, $slug] = explode(self::SEPARATOR, $reference, 2);
            if ($taxonomy !== '' && $slug !== '') {
                return [
                    'taxonomy' => sanitize_key($taxonomy),
                    'slug' => sanitize_title($slug),
                ];
            }
        }

        return self::resolveLegacySlug($reference);
    }

    /**
     * Compatibilità: slug senza tassonomia (es. offerte, blind-sponsored).
     */
    private static function resolveLegacySlug(string $slug): ?array {
        $taxonomies = get_taxonomies(['public' => true], 'names');
        foreach ($taxonomies as $taxonomy) {
            $term = get_term_by('slug', $slug, $taxonomy);
            if ($term && !is_wp_error($term)) {
                return [
                    'taxonomy' => $taxonomy,
                    'slug' => $slug,
                ];
            }
        }

        return null;
    }

    /**
     * @param string[] $references
     * @return string[] Valori normalizzati taxonomy:slug
     */
    public static function normalizeList(array $references): array {
        $normalized = [];
        foreach ($references as $ref) {
            if (!is_string($ref) || $ref === '') {
                continue;
            }
            $parsed = self::parse($ref);
            if ($parsed === null) {
                continue;
            }
            $normalized[] = self::encode($parsed['taxonomy'], $parsed['slug']);
        }

        return array_values(array_unique($normalized));
    }

    public static function formatLabel(string $reference): string {
        $parsed = self::parse($reference);
        if ($parsed === null) {
            return $reference;
        }

        $term = get_term_by('slug', $parsed['slug'], $parsed['taxonomy']);
        $taxonomy_obj = get_taxonomy($parsed['taxonomy']);
        $taxonomy_label = $taxonomy_obj ? $taxonomy_obj->labels->singular_name : $parsed['taxonomy'];

        if ($term && !is_wp_error($term)) {
            return $taxonomy_label . ' -> ' . $term->name;
        }

        return $parsed['taxonomy'] . ' -> ' . $parsed['slug'];
    }

    /**
     * Raggruppa per tassonomia → term_id[].
     *
     * @param string[] $references
     * @return array<string, int[]>
     */
    public static function groupTermIdsByTaxonomy(array $references): array {
        $groups = [];

        foreach (self::normalizeList($references) as $ref) {
            $parsed = self::parse($ref);
            if ($parsed === null) {
                continue;
            }

            $term = get_term_by('slug', $parsed['slug'], $parsed['taxonomy']);
            if ($term && !is_wp_error($term)) {
                $groups[$term->taxonomy][] = (int) $term->term_id;
            }
        }

        return $groups;
    }
}
