<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Exporter\Queries;

use BadamSoft\WooProductExporter\Filters\FilterManager;

class QueryBuilder {
    private FilterManager $filter_manager;

    public function __construct( FilterManager $filter_manager ) {
        $this->filter_manager = $filter_manager;
    }

    /**
     * Build WP_Query args for exporting products.
     *
     * @param array<string, mixed> $filters
     * @param int                  $per_page
     * @return array<string, mixed>
     */
    public function build_product_query_args( array $filters, int $per_page ): array {
        $args = [
            'post_type'      => 'product',
            'post_status'    => [ 'publish', 'private' ],
            'posts_per_page' => $per_page,
            'paged'          => 1,
            'fields'         => 'ids',
        ];

        $tax_query = $this->filter_manager->build_tax_query( $filters );

        if ( ! empty( $tax_query ) ) {
            $args['tax_query'] = $tax_query;
        }

        $meta_query = $this->filter_manager->build_meta_query( $filters );

        if ( ! empty( $meta_query ) ) {
            $args['meta_query'] = $meta_query;
        }

        $date_query = $this->filter_manager->build_date_query( $filters );

        if ( ! empty( $date_query ) ) {
            $args['date_query'] = $date_query;
        }

        if ( ! empty( $filters['incremental'] ) && ! empty( $filters['incremental_field'] ) && ! empty( $filters['incremental_anchor'] ) ) {
            $column = 'post_modified';

            if ( 'post_date' === $filters['incremental_field'] ) {
                $column = 'post_date';
            }

            $args['date_query'][] = [
                'column'    => $column,
                'after'     => $filters['incremental_anchor'],
                'inclusive' => true,
            ];
        }

        $search = isset( $filters['description_search'] ) ? trim( (string) $filters['description_search'] ) : '';

        if ( '' !== $search ) {
            $args['s']               = $search;
            $args['search_columns']   = [ 'post_content', 'post_excerpt' ];
            $args['exact']            = false;
            $args['sentence']         = false;
        }

        return apply_filters( 'prodexfo_query_args', $args, $filters );
    }
}
