<?php

namespace ModernFields\FieldGroups\Factories;

use ModernFields\FieldGroups\Repositories\UserRepository;

/**
 * Builds WordPress query arguments for retrieving field groups based on term/taxonomy locations.
 *
 * This builder prepares query arguments that filter field groups by location, scope and targets
 * for taxonomy-based field groups.
 * 
 * @since 1.0.0
 */
class TermQueryFactory extends QueryFactory
{
  /**
   * Constructor
   * 
   * @since 1.0.0
   * @param string $taxonomy The taxonomy string used to determine field group locations (default: category)
   */
  public function __construct(
    protected string $taxonomy = 'category',
  ) {}

  /**
   * Prepares WordPress query arguments for retrieving field groups.
   *
   * Combines the provided meta query with base meta queries for taxonomy location type
   * and optionally user roles. The resulting array can be used with WordPress query functions
   * like `get_posts()` or `WP_Query`.
   * 
   * @since 1.0.0
   *
   * @param array<string, mixed> $additional_meta_args Additional meta query conditions to merge with base meta query arguments
   * @return array<string, mixed> WordPress query arguments array
   */
  protected function prepareArgs(array $additional_meta_args): array
  {
    $current_user = UserRepository::getCurrentLoggedInUser();

    $base_meta_query = [
      'relation' => 'AND',
      [
        'key' => 'mf_location',
        'value' => 'taxonomy',
        'compare' => '='
      ],
      [
        'key' => 'mf_roles',
        'value' => $current_user->getRoles(),
        'compare' => 'IN'
      ]
    ];

    $meta_query = array_merge($base_meta_query, $additional_meta_args);

    $query = [
      'post_type' => MODERN_FIELDS_CPT_SLUG,
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'meta_query' => $meta_query,
    ];

    return $query;
  }

  /**
   * Builds query arguments for field groups with 'all' scope.
   *
   * Returns field groups that apply to all taxonomies.
   * 
   * @since 1.0.0
   * @return self
   */
  public function getAllTaxonomiesQuery(): self
  {
    $query = $this->prepareArgs([
      [
        'key' => 'mf_scope',
        'value' => 'all',
        'compare' => '='
      ]
    ]);

    return $this->addQuery($query);
  }

  /**
   * Builds query arguments for field groups targeting a specific taxonomy.
   *
   * Returns field groups that are configured to apply to the current term's taxonomy.
   * The taxonomy is stored as the first element in the targets array.
   * 
   * @since 1.0.0
   * @return self
   */
  public function getSpecificTaxonomyQuery(): self
  {
    $query = $this->prepareArgs([
      [
        'key' => 'mf_targets',
        'value' => $this->taxonomy,
        'compare' => '='
      ]
    ]);

    return $this->addQuery($query);
  }
}
