<?php
/**
 * Bounded batch slicing for multi-page Bricks writes.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Support;

/**
 * Same progress shape as rebuildDesignIndex: done, total, finished.
 */
final class BatchProgress
{
    public const DEFAULT_BATCH_SIZE = 5;

    /**
     * @param array<int, mixed> $items
     * @return array<int, mixed>
     */
    public static function slice(array $items, int $offset, int $batchSize): array
    {
        $offset    = max(0, $offset);
        $batchSize = max(1, $batchSize);

        return array_values(array_slice($items, $offset, $batchSize));
    }

    public static function batchSize(array $params): int
    {
        $size = (int) ($params['batch_size'] ?? self::DEFAULT_BATCH_SIZE);

        return max(1, min(20, $size));
    }

    public static function offset(array $params): int
    {
        return max(0, (int) ($params['offset'] ?? 0));
    }

    /**
     * @param string[] $names
     */
    public static function joinNames(array $names): string
    {
        $names = array_values(array_filter($names, static fn (string $name): bool => $name !== ''));
        if ($names === []) {
            return 'those pages';
        }

        if (count($names) === 1) {
            return $names[0];
        }

        $last = array_pop($names);

        return implode(', ', $names) . ' and ' . $last;
    }
}
