<?php

namespace ModernFields\FieldGroups\Factories;

use ModernFields\FieldGroups\Entities\FieldGroup;

/**
 * Factory for building and executing WordPress queries to retrieve field groups.
 *
 * This class collects WordPress query arguments and executes them to retrieve
 * field group posts, converting them into FieldGroup entities.
 *
 * @since 1.0.0
 */
class QueryFactory
{

  /**
   * Array of WordPress query arguments to be executed.
   *
   * @var array<int, array<string, mixed>>
   */
  protected array $queries = [];

  /**
   * Adds a WordPress query to the collection.
   *
   * @since 1.0.0
   * @param array<string, mixed> $query WordPress query arguments compatible with get_posts()
   * @return self
   */
  public function addQuery(array $query): self
  {
    $this->queries[] = $query;
    return $this;
  }

  /**
   * Returns all collected queries.
   *
   * @since 1.0.0
   * @return array<int, array<string, mixed>> Array of WordPress query arguments
   */
  public function getQueries(): array
  {
    return $this->queries;
  }

  /**
   * Executes all collected queries and returns FieldGroup entities.
   *
   * Filters out null queries, executes each query using get_posts(), merges
   * all results, and converts WP_Post objects into FieldGroup entities.
   *
   * @since 1.0.0
   * @return array<int, FieldGroup> Array of FieldGroup entities
   */
  public function executeQueries(): array
  {
    $posts_results = array_map(fn($query) => get_posts($query), $this->getQueries());
    $posts = array_merge(...$posts_results);
    $field_groups = array_map(fn($post) => new FieldGroup($post), $posts);

    return $field_groups;
  }
}
