<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Helpers;

use WP_Query;

class ChunkQuery {
    public const DEFAULT_PER_PAGE = 200;

    /**
     * Iterate over product IDs in manageable chunks.
     *
     * @param array<string, mixed> $args      Additional WP_Query args.
     * @param callable             $callback  Callback receiving product ID.
     * @param int                  $per_page  Items per page.
     */
    public static function loop( array $args, callable $callback, int $per_page = self::DEFAULT_PER_PAGE ): void {
        $page = 1;

        if ( isset( $args['posts_per_page'] ) ) {
            $per_page = max( 1, (int) $args['posts_per_page'] );
        }

        $base_args = array_merge(
            [
                'post_type'      => 'product',
                'post_status'    => [ 'publish', 'private' ],
                'posts_per_page' => $per_page,
                'paged'          => $page,
                'fields'         => 'ids',
            ],
            $args
        );

        do {
            $query_args = $base_args;
            $query_args['paged'] = $page;

            $query = new WP_Query( $query_args );

            if ( ! $query->have_posts() ) {
                break;
            }

            foreach ( $query->posts as $product_id ) {
                $callback( (int) $product_id );
            }

            wp_reset_postdata();
            $page++;
        } while ( $query->max_num_pages >= $page );
    }
}
