<?php
/**
 * Product ID query for feed generation.
 *
 * @package Kramar
 * @since   1.0.0
 */

declare( strict_types=1 );

namespace Kramar\Modules\Marketing;

// Prevent direct access.
defined( 'ABSPATH' ) || exit;

/**
 * Fetches product IDs for feed generation using a memory-safe WP_Query.
 *
 * Returns only simple + variable product parents (not variation post IDs).
 * Variations are expanded downstream by Variation_Handler.
 *
 * @since 1.0.0
 */
final class Product_Query {

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param Feed_Config $cfg Module configuration.
	 */
	public function __construct( private Feed_Config $cfg ) {}

	/**
	 * Return all eligible product IDs.
	 *
	 * Uses WP_Query with fields=ids and disabled caches to minimise memory.
	 *
	 * @since 1.0.0
	 *
	 * @return array<int> Product post IDs.
	 */
	public function get_ids(): array {
		$args = [
			'post_type'              => 'product',
			'post_status'            => 'publish',
			'posts_per_page'         => -1,
			'fields'                 => 'ids',
			'no_found_rows'          => true,
			'cache_results'          => false,
			'update_post_meta_cache' => false,
			'update_post_term_cache' => false,
			// Exclude hidden-from-catalog products via product visibility taxonomy.
			// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
			'tax_query'              => [
				[
					'taxonomy' => 'product_visibility',
					'field'    => 'name',
					'terms'    => [ 'exclude-from-catalog' ],
					'operator' => 'NOT IN',
				],
			],
			// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
		];

		if ( ! $this->cfg->include_out_of_stock() ) {
			// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_query
			$args['meta_query'] = [
				[
					'key'     => '_stock_status',
					'value'   => 'outofstock',
					'compare' => '!=',
				],
			];
			// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_query
		}

		$query = new \WP_Query( $args );

		return array_map( 'intval', $query->posts );
	}
}
