<?php

declare(strict_types=1);

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

namespace App\Support;

use App\Business\Report\QueryCenterService;
use App\Filament\Resources\DberpInventoryBalances\DberpInventoryBalanceResource;
use App\Filament\Resources\DberpProducts\DberpProductResource;
use App\Models\DberpProduct;
use App\Models\DberpProductSku;
use Illuminate\Database\Eloquent\Model;

final class DberpProductOperationSourceUrlResolver
{
    public static function productViewUrl(Model $record): ?string
    {
        $productId = self::resolveProductId($record);

        if ($productId <= 0) {
            return null;
        }

        return DberpProductResource::getUrl('view', ['record' => $productId]);
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function inventoryBalanceIndexUrl(Model $record, array $tableFilters = []): ?string
    {
        $productId = self::resolveProductId($record);

        if ($productId <= 0) {
            return null;
        }

        $parsed = QueryCenterService::productOperationFiltersFromTableState($tableFilters);

        $filters = [
            'product_id' => ['value' => $productId],
        ];

        if ($record instanceof DberpProductSku) {
            $filters['product_sku_id'] = ['value' => (int) $record->getKey()];
        }

        if (($parsed['warehouse_id'] ?? 0) > 0) {
            $filters['warehouse_id'] = ['value' => (int) $parsed['warehouse_id']];
        }

        return DberpFilamentListPageUrl::append(DberpInventoryBalanceResource::getUrl('index'), $filters);
    }

    private static function resolveProductId(Model $record): int
    {
        if ($record instanceof DberpProductSku) {
            return (int) $record->product_id;
        }

        if ($record instanceof DberpProduct) {
            return (int) $record->getKey();
        }

        if ($record->getAttribute('product_id') !== null) {
            return (int) $record->getAttribute('product_id');
        }

        return (int) $record->getKey();
    }
}
