<?php

namespace App\Models;

use App\Helpers\Strings;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Favorite extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable
     *
     * @var array<string, string>
     */
    protected $fillable = [
        'user_id',
        'favoritable_id',
        'favoritable_type'
    ];

    /**
     * Booted method of the model
     *
     * @return void
     */
    protected static function booted()
    {
        static::creating(function ($favorite) {
            $favorite->user_id = auth()->user()->id;
            $favorite->favoritable_type = Strings::getType($favorite->favoritable_type);
        });

        static::updating(function ($favorite) {
            $favorite->user_id = auth()->user()->id;
            $favorite->favoritable_type = Strings::getType($favorite->favoritable_type);
        });
    }

    /**
     * Get the favoritable model
     *
     * @return MorphTo
     */
    public function favoritable(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * Retrieve associated user
     *
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
