<?php

namespace ACP\Editing\RequestHandler\Query;

use AC\Request;
use ACP\Editing\ApplyFilter\RowsPerIteration;
use ACP\Editing\RequestHandler;
use ACP\Editing\Response;
use WP_Post;
use WP_Query;

final class Post implements RequestHandler
{

    private Request $request;

    public function handle(Request $request)
    {
        $this->request = $request;

        $this->register();
    }

    private function register(): void
    {
        add_action('pre_get_posts', [$this, 'set_query_vars'], PHP_INT_MAX - 100);
        add_filter('the_posts', [$this, 'send'], 10, 2);
    }

    private function get_rows_per_iteration(): int
    {
        return (new RowsPerIteration($this->request))->apply_filters(2000);
    }

    protected function get_offset(): int
    {
        $page = (int)$this->request->filter('ac_page', 1, FILTER_SANITIZE_NUMBER_INT);

        return ($page - 1) * $this->get_rows_per_iteration();
    }

    /**
     * @param WP_Post[] $posts
     * @param WP_Query  $query
     *
     * @return void|WP_Post[]
     */
    public function send($posts, WP_Query $query)
    {
        if ( ! $query->is_main_query()) {
            return $posts;
        }

        $post_ids = wp_list_pluck($posts, 'ID');

        $response = new Response\QueryRows($post_ids, $this->get_rows_per_iteration());
        $response->success();
    }

    public function set_query_vars(WP_Query $query): void
    {
        if ( ! $query->is_main_query()) {
            return;
        }

        $query->set('nopaging', false);
        $query->set('offset', $this->get_offset());
        $query->set('posts_per_page', $this->get_rows_per_iteration());
        $query->set('posts_per_archive_page', $this->get_rows_per_iteration());
        $query->set('fields', 'all');
        $query->set('suppress_filters', false);
    }

}