<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventorySummaries\Pages;

use App\Business\Report\InventoryReportService;
use App\Filament\Resources\DberpInventorySummaries\DberpInventorySummaryResource;
use App\Services\DberpPermissionService;
use App\Support\DberpInventorySummaryFilamentSupport;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class ListDberpInventorySummaries extends ListRecords
{
    protected static string $resource = DberpInventorySummaryResource::class;

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

    protected function getHeaderActions(): array
    {
        $permissions = app(DberpPermissionService::class);
        $user = Auth::user();
        $tableFilters = is_array($this->tableFilters) ? $this->tableFilters : [];

        return [
            Action::make('inventoryTransactions')
                ->label(__('dberp.resources.inventory_summary.link_transactions'))
                ->url(DberpInventorySummaryFilamentSupport::inventoryTransactionIndexUrlFromTableState($tableFilters))
                ->visible(fn (): bool => $permissions->allows($user, DberpPermissionService::NAV_INVENTORY_TRANSACTION_QUERY)),
        ];
    }

    protected function getTableQuery(): Builder
    {
        $filters = InventoryReportService::filtersFromTableState($this->tableFilters);
        $level = (string) (data_get($this->tableFilters, 'aggregate_level.value') ?? data_get($this->tableFilters, 'aggregate_level') ?? 'sku_detail');
        $service = app(InventoryReportService::class);

        if ($level === 'product_summary') {
            return $service->productSummaryQuery($filters);
        }

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