<?php

declare(strict_types=1);

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

namespace App\Business\Product;

use App\Models\DberpProduct;
use App\Models\DberpProductSku;

final class ProductBusinessSnapshot
{
    /**
     * @return array{
     *     product_id: int,
     *     product_code: string,
     *     product_name: string,
     *     product_sku_id: int,
     *     sku_code: string,
     *     spec_text: string|null
     * }
     */
    public static function identityFromSku(DberpProductSku $sku, ?DberpProduct $product = null): array
    {
        $product ??= $sku->relationLoaded('product') ? $sku->product : $sku->product()->first();
        if (! $product instanceof DberpProduct) {
            throw new \InvalidArgumentException('Product SKU must resolve to a product.');
        }

        return [
            'product_id' => (int) $product->getKey(),
            'product_code' => (string) $product->code,
            'product_name' => (string) $product->name,
            'product_sku_id' => (int) $sku->getKey(),
            'sku_code' => (string) $sku->sku_code,
            'spec_text' => $sku->spec_text !== null && $sku->spec_text !== '' ? (string) $sku->spec_text : null,
        ];
    }

    /**
     * @return array{
     *     product_id: int,
     *     product_code: string,
     *     product_name: string,
     *     product_sku_id: int,
     *     sku_code: string,
     *     spec_text: string|null,
     *     unit_id: int|null,
     *     unit_name: string|null
     * }
     */
    public static function fromSku(DberpProductSku $sku, ?DberpProduct $product = null): array
    {
        $product ??= $sku->relationLoaded('product') ? $sku->product : $sku->product()->first();
        if (! $product instanceof DberpProduct) {
            throw new \InvalidArgumentException('Product SKU must resolve to a product.');
        }

        $unit = $sku->resolveEffectiveUnit();

        return array_merge(self::identityFromSku($sku, $product), [
            'unit_id' => $unit !== null ? (int) $unit->getKey() : null,
            'unit_name' => $unit !== null ? (string) $unit->name : null,
        ]);
    }
}
