<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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);
    }
}
