<?php

declare(strict_types=1);

namespace App\Business\Product;

use App\Models\DberpProduct;
use App\Models\DberpProductSku;
use Illuminate\Validation\ValidationException;

/**
 * 在未启用多规格、或仅一条可用规格组合等可安全默认的场景，解析库存过账用的规格组合。
 *
 * 多规格且行上未带 {@see DberpProductSku} 主键时，应由 {@see InventoryPostingProductSkuResolver} 先拦截，避免静默猜默认。
 */
final class LedgerProductSkuResolver
{
    public static function defaultSkuForProductInventoryLine(DberpProduct $product): DberpProductSku
    {
        $sku = DberpProductSku::query()
            ->where('product_id', $product->getKey())
            ->where('is_enabled', true)
            ->orderByDesc('is_default')
            ->orderBy('sort_order')
            ->orderBy('id')
            ->first();

        if ($sku !== null) {
            return $sku;
        }

        if (! DberpProductSku::query()->where('product_id', $product->getKey())->exists()) {
            return DberpProductSku::createDefaultForProduct($product);
        }

        throw ValidationException::withMessages([
            'product_id' => __('dberp.errors.product_sku_all_disabled_for_inventory'),
        ]);
    }
}
