<?php

declare(strict_types=1);

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

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