<?php

namespace Modules\AiAgent\Filament\Concerns;

use Illuminate\Pagination\LengthAwarePaginator;

/**
 * Bridges a bnfexpress list response (a bare JSON array — confirmed live via
 * `php artisan bnfexpress:smoke-test` for FAQs/instructions, and the same
 * shape for suggestions/misses per their `response_model=list[...]`) into a
 * LengthAwarePaginator for Table::records(). bnfexpress reports no total
 * count, so this falls back to a "there might be one more page" heuristic —
 * also tolerates a {total, <$itemsKey>} envelope in case that ever changes.
 */
trait PaginatesBnfexpressLists
{
    /**
     * @param  array<string, mixed>  $result
     */
    private function paginateBareList(array $result, string $itemsKey, string $recordKey, int $page, int $recordsPerPage): LengthAwarePaginator
    {
        $items = $result[$itemsKey] ?? (array_is_list($result) ? $result : []);

        $total = $result['total'] ?? (($page - 1) * $recordsPerPage) + count($items) + (count($items) === $recordsPerPage ? 1 : 0);

        return new LengthAwarePaginator(
            items: collect($items)->mapWithKeys(fn (array $item): array => [$item[$recordKey] => $item]),
            total: $total,
            perPage: $recordsPerPage,
            currentPage: $page,
        );
    }
}
