<?php

declare(strict_types=1);

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,
        ]);
    }
}
