<?php

declare(strict_types=1);

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