<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ProductAttribute extends Model
{
    protected $fillable = [
        'name',
    ];

    protected static function boot()
    {
        parent::boot();

        static::updated(function ($attribute) {
            if ($attribute->wasChanged('name')) {
                $oldName = $attribute->getOriginal('name');
                $newName = $attribute->name;

                // Automatically rename keys in product_variants options JSON column
                \App\Models\ProductVariant::query()->chunk(100, function ($variants) use ($oldName, $newName) {
                    foreach ($variants as $variant) {
                        $options = $variant->options;
                        if (is_array($options) && array_key_exists($oldName, $options)) {
                            $value = $options[$oldName];
                            unset($options[$oldName]);
                            $options[$newName] = $value;
                            $variant->options = $options;
                            $variant->save();
                        }
                    }
                });
            }
        });
    }

    public function values(): HasMany
    {
        return $this->hasMany(ProductAttributeValue::class, 'product_attribute_id');
    }
}
