<?php

declare(strict_types=1);

namespace App\Filament\Support;

use App\Models\DberpInventoryBalance;
use App\Models\DberpInventoryReplenishmentSuggestion;
use App\Models\DberpInventoryRule;
use App\Models\DberpProduct;
use App\Models\DberpWarehouse;

/**
 * 组合型 Filament 记录标题（商品 + 仓库等），供无单一业务字段的库存资源使用。
 */
final class DberpFilamentRecordTitles
{
    public static function inventoryBalance(DberpInventoryBalance $record): string
    {
        $record->loadMissing(['product', 'warehouse', 'productSku']);

        $productLabel = filled($record->product?->name)
            ? (string) $record->product->name
            : (string) ($record->product?->code ?? '');

        if ($record->productSku !== null && filled($record->productSku->spec_text)) {
            $productLabel .= '（'.(string) $record->productSku->spec_text.'）';
        }

        if (filled($record->warehouse?->name)) {
            return $productLabel.' · '.(string) $record->warehouse->name;
        }

        return $productLabel !== '' ? $productLabel : '—';
    }

    public static function inventoryRule(DberpInventoryRule $record): string
    {
        $record->loadMissing(['product', 'warehouse']);

        return self::productWithWarehouse($record->product, $record->warehouse);
    }

    public static function inventoryReplenishmentSuggestion(DberpInventoryReplenishmentSuggestion $record): string
    {
        $record->loadMissing(['product', 'warehouse']);

        return self::productWithWarehouse($record->product, $record->warehouse);
    }

    private static function productWithWarehouse(?DberpProduct $product, ?DberpWarehouse $warehouse): string
    {
        $productLabel = filled($product?->name)
            ? (string) $product->name
            : (string) ($product?->code ?? '');

        if (filled($warehouse?->name)) {
            return $productLabel !== ''
                ? $productLabel.' · '.(string) $warehouse->name
                : (string) $warehouse->name;
        }

        return $productLabel !== '' ? $productLabel : '—';
    }
}
