<?php
/**
 * Index maintenance handler.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Handlers;

use LolaCoreForBricks\BricksEnv;
use LolaCoreForBricks\Support\BricksCodeGuard;
use LolaCoreForBricks\Index\IndexBuilder;
use LolaCoreForBricks\Index\IndexReader;

/**
 * Executes rebuildDesignIndex batch logic.
 */
class IndexHandler
{
    public function __construct(
        private readonly ?IndexBuilder $builder = null,
        private readonly ?IndexReader $reader = null
    ) {
    }

    /**
     * @param array<string, mixed> $params
     * @return array<string, mixed>
     */
    public function rebuildDesignIndex(array $params = [], bool $dryRun = false): array
    {
        if ($rejection = BricksCodeGuard::rejectionResponse($params)) {
            return $rejection;
        }

        if (!BricksEnv::userCanReadDesignSystem()) {
            return [
                'success' => false,
                'message' => 'I need administrator access to rebuild the Bricks design index.',
            ];
        }

        if ($dryRun) {
            $coverage = ($this->reader ?? new IndexReader())->coverage();

            return [
                'success'    => true,
                'message'    => 'Index rebuild preview is ready. Call again without dry_run to advance the next batch.',
                'done'       => $coverage['indexed'],
                'total'      => $coverage['total'],
                'finished'   => $coverage['complete'],
                'elapsed_ms' => 0,
                'coverage'   => $coverage,
            ];
        }

        $result = ($this->builder ?? new IndexBuilder())->buildBatch($params);

        return array_merge(
            [
                'success' => true,
                'message' => ($result['finished'] ?? false)
                    ? 'Bricks design index is fully built.'
                    : 'Bricks design index batch completed. Call again until finished is true.',
            ],
            $result
        );
    }
}
