<?php

declare(strict_types=1);

namespace App\Business\Inventory;

use App\Business\Product\DberpProductUnitConversionService;
use Illuminate\Database\Eloquent\Model;

/**
 * 库存流水：保留「录入单位/数量」与过账时换算快照（主单位数量仍由台账 change_quantity 表达）。
 */
final readonly class InventoryLedgerLineTrace
{
    public function __construct(
        public string $documentInputQuantity,
        public int $documentInputUnitId,
        public string $documentInputUnitName,
        public int $postingBaseUnitId,
        public ?int $postingAuxiliaryUnitId,
        public bool $postingIsAuxiliaryUnit,
        public ?string $postingAuxiliaryUnitQuantity,
        public ?string $postingBaseUnitQuantity,
    ) {}

    public static function fromDocumentLine(
        Model $line,
        string $documentQuantityField,
    ): self {
        $qty = DberpProductUnitConversionService::formatQuantityOrZero(
            (string) ($line->getAttribute($documentQuantityField) ?? ''),
            4,
        );

        return new self(
            documentInputQuantity: $qty,
            documentInputUnitId: (int) ($line->getAttribute('unit_id') ?? 0),
            documentInputUnitName: trim((string) ($line->getAttribute('unit_name') ?? '')),
            postingBaseUnitId: (int) ($line->getAttribute('base_unit_id') ?? 0),
            postingAuxiliaryUnitId: self::nullableInt($line->getAttribute('auxiliary_unit_id')),
            postingIsAuxiliaryUnit: (bool) $line->getAttribute('is_auxiliary_unit'),
            postingAuxiliaryUnitQuantity: self::nullableNumericString($line->getAttribute('auxiliary_unit_quantity')),
            postingBaseUnitQuantity: self::nullableNumericString($line->getAttribute('base_unit_quantity')),
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function toTransactionAttributes(): array
    {
        return [
            'document_input_quantity' => $this->documentInputQuantity,
            'document_input_unit_id' => $this->documentInputUnitId > 0 ? $this->documentInputUnitId : null,
            'document_input_unit_name' => $this->documentInputUnitName !== '' ? $this->documentInputUnitName : null,
            'posting_base_unit_id' => $this->postingBaseUnitId > 0 ? $this->postingBaseUnitId : null,
            'posting_auxiliary_unit_id' => $this->postingAuxiliaryUnitId,
            'posting_is_auxiliary_unit' => $this->postingIsAuxiliaryUnit,
            'posting_auxiliary_unit_quantity' => $this->postingAuxiliaryUnitQuantity,
            'posting_base_unit_quantity' => $this->postingBaseUnitQuantity,
        ];
    }

    private static function nullableInt(mixed $value): ?int
    {
        if ($value === null || $value === '') {
            return null;
        }

        $int = (int) $value;

        return $int > 0 ? $int : null;
    }

    private static function nullableNumericString(mixed $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        $string = is_string($value) ? trim($value) : trim((string) $value);
        if ($string === '' || ! is_numeric($string)) {
            return null;
        }

        return $string;
    }
}
