<?php

declare(strict_types=1);

namespace App\Support;

use App\Models\DberpInventoryTransaction;

/**
 * 库存流水：录入侧与过账换算快照的界面展示（来自流水表字段，不随商品档案变更）。
 */
final class DberpInventoryTransactionPresentation
{
    public static function documentEnteredDisplay(DberpInventoryTransaction $record): string
    {
        $qty = $record->document_input_quantity;
        if ($qty === null || $qty === '') {
            return (string) __('dberp.messages.inventory_ledger_no_entered_trace');
        }

        $qtyStr = is_string($qty) ? trim($qty) : trim((string) $qty);
        if ($qtyStr === '' || ! is_numeric($qtyStr)) {
            return (string) __('dberp.messages.inventory_ledger_no_entered_trace');
        }

        $unit = trim((string) ($record->document_input_unit_name ?? ''));
        if ($unit === '') {
            $rel = $record->relationLoaded('documentInputUnit') ? $record->documentInputUnit : $record->documentInputUnit()->first();
            $unit = trim((string) ($rel?->name ?? ''));
        }

        return $unit === ''
            ? DberpNumberFormatter::quantity($qtyStr)
            : DberpNumberFormatter::quantity($qtyStr).' '.$unit;
    }

    public static function postingConversionSnapshotDisplay(DberpInventoryTransaction $record): string
    {
        if (! (bool) $record->posting_is_auxiliary_unit) {
            return (string) __('dberp.messages.inventory_ledger_no_auxiliary_posting');
        }

        $baseId = (int) ($record->posting_base_unit_id ?? 0);
        $auxId = (int) ($record->posting_auxiliary_unit_id ?? 0);
        $text = DberpProductAuxiliaryUnitPreview::fromSnapshot(
            $baseId,
            $auxId,
            $record->posting_auxiliary_unit_quantity,
            $record->posting_base_unit_quantity,
        );

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

    public static function primaryBaseChangeDisplay(DberpInventoryTransaction $record): string
    {
        $qty = (string) ($record->change_quantity ?? '0');
        $unit = trim((string) ($record->unit_name ?? ''));

        return $unit === ''
            ? DberpNumberFormatter::quantity($qty)
            : DberpNumberFormatter::quantity($qty).' '.$unit;
    }
}
