<?php

namespace App\Models;

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

class SpecificationValue extends Model
{
    use HasFactory;

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

    protected $casts = [
        'product_id' => 'integer',
        'specification_key_id' => 'integer',
    ];

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

        static::saved(function ($specificationValue) {
            Cache::forget('product_' . $specificationValue->product_id . '_specification_key_values_' . $specificationValue->specification_key_id);
        });

        static::deleted(function ($specificationValue) {
            Cache::forget('product_' . $specificationValue->product_id . '_specification_key_values_' . $specificationValue->specification_key_id);
        });
    }

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

    public function specificationKey(): BelongsTo
    {
        return $this->belongsTo(SpecificationKey::class);
    }
}
