<?php

namespace NewsletterBridge\Services\Query;

use NewsletterBridge\Interfaces\QueryBuilderInterface;
use NewsletterBridge\Services\Query\DateRangeBuilder;
use NewsletterBridge\Services\Query\TaxonomyQueryBuilder;

/**
 * Responsabilità: Costruzione delle query WordPress
 * Single Responsibility: Solo logica di costruzione query
 * Refactored: Usa composizione per separare responsabilità
 */
class QueryBuilder implements QueryBuilderInterface {
    
    private DateRangeBuilder $dateRangeBuilder;
    private TaxonomyQueryBuilder $taxonomyBuilder;
    private array $baseArgs;
    
    public function __construct(
        DateRangeBuilder $dateRangeBuilder,
        TaxonomyQueryBuilder $taxonomyBuilder
    ) {
        $this->dateRangeBuilder = $dateRangeBuilder;
        $this->taxonomyBuilder = $taxonomyBuilder;
        $this->baseArgs = $this->getBaseQueryArgs();
    }
    
    /**
     * Costruisce gli argomenti base per le query
     */
    private function getBaseQueryArgs(): array {
        return [
            'post_status'    => 'publish',
            'post_type'      => ['post'],
            'date_query'     => [
                $this->dateRangeBuilder->buildDateRange()
            ]
        ];
    }
    
    /**
     * Costruisce una query completa per un feed specifico
     */
    public function buildQuery(string $feed_name, array $feed_config, array $used_posts = []): array {
        $args = $this->baseArgs;
        
        // Applica parametri specifici del feed
        if (isset($feed_config['query_params'])) {
            $args = $this->applyFeedParams($args, $feed_config['query_params']);
        }
        
        // Esclude post già utilizzati
        if (!empty($used_posts)) {
            $args['post__not_in'] = $used_posts;
        }
        
        return $args;
    }
    
    /**
     * Applica i parametri specifici del feed alla query
     */
    private function applyFeedParams(array $args, object $query_params): array {
        // Posts per page
        if (isset($query_params->posts_per_page)) {
            $args['posts_per_page'] = $query_params->posts_per_page;
        }
        
        // Post types
        if (isset($query_params->post_types)) {
            $args['post_type'] = $query_params->post_types;
        }
        
        // Tassonomie da includere
        $include_taxonomies = $query_params->include_taxonomies ?? $query_params->include_tags ?? null;
        if ($include_taxonomies) {
            // Converte stdClass in array se necessario
            if (is_object($include_taxonomies)) {
                $include_taxonomies = (array) $include_taxonomies;
            }
            // Assicura che sia un array
            if (!is_array($include_taxonomies)) {
                $include_taxonomies = [$include_taxonomies];
            }
            
            $include_query = $this->taxonomyBuilder->buildIncludeQuery($include_taxonomies);
            if (!empty($include_query)) {
                $args['tax_query'] = $this->taxonomyBuilder->combineTaxQueries($args['tax_query'] ?? [], $include_query);
            }
        }
        
        // Tassonomie da escludere
        $exclude_taxonomies = $query_params->exclude_taxonomies ?? $query_params->exclude_tags ?? null;
        if ($exclude_taxonomies) {
            // Converte stdClass in array se necessario
            if (is_object($exclude_taxonomies)) {
                $exclude_taxonomies = (array) $exclude_taxonomies;
            }
            // Assicura che sia un array
            if (!is_array($exclude_taxonomies)) {
                $exclude_taxonomies = [$exclude_taxonomies];
            }
            
            $exclude_query = $this->taxonomyBuilder->buildExcludeQuery($exclude_taxonomies);
            if (!empty($exclude_query)) {
                $args['tax_query'] = $this->taxonomyBuilder->combineTaxQueries($args['tax_query'] ?? [], $exclude_query);
            }
        }
        
        // Meta query personalizzata
        if (isset($query_params->meta_query)) {
            $args['meta_query'] = $query_params->meta_query;
        }
        
        return $args;
    }
}
