<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class SpecificationKey extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'specification_id',
        'key',
        'default_value',
    ];

    protected $casts = [
        'specification_id' => 'integer',
    ];

    /**
     * remove cache data in update
     */
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($specificationKey) {
            Cache::forget('specification_keys_' . $specificationKey->specification_id);

            // category appends
            Cache::forget('get_category_specifications_' . $specificationKey->specification->category_id);
            Cache::forget('category_childs_' . $specificationKey->specification->category_id);
        });

        static::deleted(function ($specificationKey) {
            Cache::forget('specification_keys_' . $specificationKey->specification_id);

            // category appends
            Cache::forget('get_category_specifications_' . $specificationKey->specification->category_id);
            Cache::forget('category_childs_' . $specificationKey->specification->category_id);
        });
    }

    /* relationships **************/
    public function specification(): BelongsTo
    {
        return $this->belongsTo(Specification::class);
    }

    public function specificationValues(): HasMany
    {
        return $this->hasMany(SpecificationValue::class);
    }
}
