<?php

namespace App\Support;

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Collection;

final class LimitedQuery
{
    /**
     * @param  EloquentBuilder|QueryBuilder  $query
     * @return array{rows: Collection, truncated: bool}
     */
    public static function get(EloquentBuilder|QueryBuilder $query, int $limit): array
    {
        $limit = max(1, $limit);
        $rows = (clone $query)->limit($limit + 1)->get();
        $truncated = $rows->count() > $limit;

        return [
            'rows' => $truncated ? $rows->take($limit)->values() : $rows,
            'truncated' => $truncated,
        ];
    }
}
