<?php

namespace NewsletterBridge\Services\Query;

/**
 * Responsabilità: Costruzione query tassonomie
 * Single Responsibility: Solo logica tassonomie
 */
class TaxonomyQueryBuilder {
    
    /**
     * Costruisce query per tassonomie da includere
     */
    public function buildIncludeQuery(array $include_taxonomies): array {
        return $this->buildTaxonomyQuery($include_taxonomies, 'IN', 'OR');
    }
    
    /**
     * Costruisce query per tassonomie da escludere
     */
    public function buildExcludeQuery(array $exclude_taxonomies): array {
        return $this->buildTaxonomyQuery($exclude_taxonomies, 'NOT IN', 'AND');
    }
    
    /**
     * Costruisce query tassonomie generica
     */
    private function buildTaxonomyQuery(array $taxonomies, string $operator, string $relation): array {
        $tax_query = [];
        $taxonomies_groups = $this->groupTaxonomiesByType($taxonomies);
        
        // Crea la tax_query per ogni tassonomia
        foreach ($taxonomies_groups as $taxonomy => $term_ids) {
            $tax_query[] = [
                'taxonomy' => $taxonomy,
                'field' => 'term_id',
                'terms' => $term_ids,
                'operator' => $operator
            ];
        }
        
        if (!empty($tax_query)) {
            $tax_query['relation'] = $relation;
        }
        
        return $tax_query;
    }
    
    /**
     * Raggruppa i termini per tassonomia
     */
    private function groupTaxonomiesByType(array $taxonomies): array {
        $groups = [];
        
        foreach ($taxonomies as $term_slug) {
            $term = get_term_by('slug', $term_slug);
            if ($term) {
                $groups[$term->taxonomy][] = $term->term_id;
            }
        }
        
        return $groups;
    }
    
    /**
     * Combina query tassonomie esistenti
     */
    public function combineTaxQueries(array $existing_query, array $new_query): array {
        if (empty($new_query)) {
            return $existing_query;
        }
        
        if (empty($existing_query)) {
            return $new_query;
        }
        
        return [
            'relation' => 'AND',
            $existing_query,
            $new_query
        ];
    }
}
