<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSupplierPurchaseRankings\Pages;

use App\Business\Report\PurchaseReportService;
use App\Filament\Resources\DberpSupplierPurchaseRankings\DberpSupplierPurchaseRankingResource;
use App\Models\DberpSupplier;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;

class ListDberpSupplierPurchaseRankings extends ListRecords
{
    protected static string $resource = DberpSupplierPurchaseRankingResource::class;

    public function getSubheading(): string|Htmlable|null
    {
        return __('dberp.resources.supplier_purchase_ranking.scope_hint');
    }

    public function computeSupplierPurchaseRankingRank(DberpSupplier $record): int
    {
        $paginator = $this->getTableRecords();

        if (! $paginator instanceof LengthAwarePaginator) {
            return 0;
        }

        $perPage = max(1, $paginator->perPage());
        $offset = max(0, ($paginator->currentPage() - 1) * $perPage);

        foreach ($paginator->items() as $index => $item) {
            if ($item instanceof DberpSupplier && $item->getKey() === $record->getKey()) {
                return $offset + $index + 1;
            }
        }

        return 0;
    }

    protected function getTableQuery(): Builder
    {
        return app(PurchaseReportService::class)->supplierRankingQuery(
            PurchaseReportService::filtersFromTableState(
                is_array($this->tableFilters) ? $this->tableFilters : null,
            ),
        );
    }
}
