<?php

namespace App\Models\Ecommerce\Product\Property;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ProductAttributeValue extends Model
{
    use HasFactory;

    /**
     * Table name
     */
    protected $table = 'attribute_value_product_attribute';

    /**
     * Indicates if the model should be timestamped.
     */
    public $timestamps = false;

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

    /**
     * The relations to eager load on every query.
     */
    protected $with = ['value'];

    /**
     * The accessors to append to the model's array form.
     */
    protected $appends = ['real_value'];

    /**
     * Return exact product attribute value.
     *
     * @return string|int
     */
    public function realValue(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->product_custom_value ?: ($this->value?->value ?? '')
        );
    }

    /**
     * Attribute Value for forms
     */
    public function valueForForms(): null|int|string
    {
        return $this->product_custom_value ?: $this->attribute_value_id;
    }

    /**
     * Value
     */
    public function value(): BelongsTo
    {
        return $this->belongsTo(AttributeValue::class, 'attribute_value_id');
    }
}
