<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpProductPurchaseRankings\Pages;

use App\Business\Report\PurchaseReportService;
use App\Filament\Resources\DberpProductPurchaseRankings\DberpProductPurchaseRankingResource;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;

class ListDberpProductPurchaseRankings extends ListRecords
{
    protected static string $resource = DberpProductPurchaseRankingResource::class;

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

    public function computeProductPurchaseRankingRank(Model $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 Model) {
                continue;
            }

            if ($item->getKey() === $record->getKey() && $item::class === $record::class) {
                return $offset + $index + 1;
            }
        }

        return 0;
    }

    protected function getTableQuery(): Builder
    {
        $filters = PurchaseReportService::filtersFromTableState(
            is_array($this->tableFilters) ? $this->tableFilters : null,
        );

        $level = (string) (data_get($this->tableFilters, 'ranking_dimension.value') ?? data_get($this->tableFilters, 'ranking_dimension') ?? 'product');
        $service = app(PurchaseReportService::class);

        if ($level === 'product_spec') {
            return $service->productSkuRankingQuery($filters);
        }

        return $service->productRankingQuery($filters);
    }
}
