<?php

namespace ModernFields\FieldGroups\Factories;

use ModernFields\FieldGroups\Entities\Attachment;
use ModernFields\FieldGroups\Repositories\UserRepository;

/**
 * Builds WordPress query arguments for retrieving field groups based on post locations.
 *
 * This builder prepares query arguments that filter field groups by location, scope and targets
 * 
 * @since 1.0.0
 */
class MediaQueryFactory extends QueryFactory
{
  /**
   * Constructor
   * 
   * @since 1.0.0
   * @param Attachment $attachment The attachment entity used to determine field group locations
   */
  public function __construct(
    protected Attachment $attachment,
  ) {}

  /**
   * Prepares WordPress query arguments for retrieving field groups.
   *
   * Combines the provided meta query with base meta queries for location type
   * and user roles. The resulting array can be used with WordPress query functions
   * like `get_posts()` or `WP_Query`.
   * 
   * @since 1.0.0
   *
   * @param array $additional_meta_args Additional meta query conditions to merge with meta query arguments
   * @return array 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' => 'media',
        'compare' => '='
      ],
      [
        'key' => 'mf_roles',
        'value' => $current_user->getRoles(),
        'compare' => 'IN'
      ],
    ];

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

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

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

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

  /**
   * Builds query arguments for field groups targeting specific media types.
   * 
   * No need to add scope here as we are targeting a specific media type.
   * Returns field groups that are configured to apply to the current attachment by ID.
   * 
   * @since 1.0.0
   * @return self
   */
  public function getSpecificMediaTypeQuery(): self
  {
    $query = $this->prepareArgs([
      [
        'key' => 'mf_targets',
        'value' => $this->attachment->getMimeType(),
        'compare' => '='
      ]
    ]);

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