<?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 Specification extends Model
{
    use HasFactory;

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

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

    /**
     * additional data
     */
    protected $appends = [
        'keys',
    ];

    public function getKeysAttribute()
    {
        return $this->specificationKeys()->get()->map(fn($specificationKey) => [
            'id' => $specificationKey->id,
            'key' => $specificationKey->key,
            'value' => $specificationKey->default_value,
        ])->toArray();
    }
    /** end append */

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

        static::saved(function ($specification) {
            Cache::forget('specifications_' . $specification->category_id);

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

        static::deleted(function ($specification) {
            Cache::forget('specifications_' . $specification->category_id);

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

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

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