<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpProductSalesRankings\Pages;

use App\Business\Report\SalesReportService;
use App\Filament\Resources\DberpProductSalesRankings\DberpProductSalesRankingResource;
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 ListDberpProductSalesRankings extends ListRecords
{
    protected static string $resource = DberpProductSalesRankingResource::class;

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

    public function computeProductSalesRankingRank(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 = SalesReportService::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(SalesReportService::class);

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

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