<?php

namespace App\Support;

use App\Models\Catalog\Product;
use App\Models\Catalog\ProductAttribute;

/**
 * Ported verbatim from App\Http\Controllers\Isms\ProductController::syncAttributes()
 * — replace a product's custom attribute rows wholesale (delete + reinsert)
 * rather than diffing, since the form always resubmits the full current list.
 */
class ProductAttributeSync
{
    /**
     * @param  array<int, array{key?: string, value?: string|null}>  $attributes
     */
    public static function apply(Product $product, array $attributes): void
    {
        $product->attributes()->delete();

        $rows = [];
        $order = 0;
        foreach ($attributes as $attribute) {
            $key = trim((string) ($attribute['key'] ?? ''));
            if ($key === '') {
                continue;
            }
            $rows[] = [
                'product_id' => $product->id,
                'key' => $key,
                'value' => $attribute['value'] ?? null,
                'sort_order' => $order++,
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        if ($rows !== []) {
            ProductAttribute::insert($rows);
        }
    }
}
