<?php

namespace App\Models\Polymorphs;

use App\Models\Traits\Bootables\Auditable;
use App\Models\Traits\Bootables\Authorable;
use App\Models\Traits\Bootables\Statuable;
use App\Models\Traits\HasAutors;
use App\Models\Traits\HasDates;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User;
use Spatie\MediaLibrary\HasMedia as SpatieHasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Comment extends Model implements SpatieHasMedia{
    use HasFactory,SoftDeletes,HasDates,
        InteractsWithMedia,
       Authorable,Auditable,Statuable;

    protected $guarded = ['id','created_at'];
    const TABLE_NAME = "comments";
    protected $table= self::TABLE_NAME;
    const MORPH_ID_COLUMN = "commentable_id";
    const MORPH_TYPE_COLUMN = "commentable_type";
    const MORPH_FUNCTION_NAME = "commentable";


    public function commentable(){
        return $this->morphTo(__FUNCTION__,
            self::MORPH_TYPE_COLUMN,self::MORPH_ID_COLUMN);
    }

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

    /**
     * Determine if this comment is written by the specified user.
     *
     * @param  $user
     * @return boolean
     */
    public function isWrittenBy($user){
        return $user->is($this->author);
    }

}
