<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Comment extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable
     *
     * @var array<string, string>
     */
    protected $fillable = [
        'uuid',
        'user_id',
        'comment',
        'parent_id',
        'commentable_id',
        'commentable_type'
    ];

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

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

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

    /**
     * Retrieve associated parent
     *
     * @return BelongsTo
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Comment::class, 'parent_id');
    }

    /**
     * Retrieve associated children
     *
     * @return HasMany
     */
    public function children(): HasMany
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }

    /**
     * Retreive recursive children
     *
     * @return object
     */
    public function childrenRecursive(): object
    {
        return $this->children()->with('childrenRecursive');
    }
}
