<?php

declare(strict_types=1);

namespace App\Business\Product;

use App\Models\DberpProduct;
use App\Models\DberpProductSku;
use Illuminate\Support\Facades\DB;

/**
 * 单规格模式下默认规格组合与主档摘要字段的维护。
 */
final class ProductSkuLifecycleService
{
    public function syncAfterProductSaved(DberpProduct $product): void
    {
        if ($product->spec_enabled) {
            return;
        }

        $this->enforceSingleSpecMode($product);
    }

    public function enforceSingleSpecMode(DberpProduct $product): void
    {
        DB::transaction(function () use ($product): void {
            DberpProductSku::createDefaultForProduct($product);

            $skus = DberpProductSku::query()
                ->where('product_id', $product->getKey())
                ->orderBy('sort_order')
                ->orderBy('id')
                ->get();

            if ($skus->isEmpty()) {
                return;
            }

            $default = $skus->firstWhere('is_default', true) ?? $skus->first();
            if ($default === null) {
                return;
            }

            foreach ($skus as $sku) {
                if ($sku->is($default)) {
                    $sku->forceFill([
                        'is_default' => true,
                        'is_enabled' => (bool) $product->is_enabled,
                        'spec_text' => $product->spec_model,
                    ])->save();

                    continue;
                }

                $hasStock = ProductSkuReferenceGuard::hasPositiveRealtimeStock((int) $sku->getKey());

                $sku->forceFill([
                    'is_default' => false,
                    'is_enabled' => $hasStock ? (bool) $sku->getAttribute('is_enabled') : false,
                ])->save();
            }
        });
    }
}
