<?php

namespace App\Models;

use App\Models\Concerns\Reportable;
use Illuminate\Database\Eloquent\Collection;

/**
 * Comment on a data table
 *
 * @property int $id
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property int $table_id
 * @property int $author_id
 * @property int $ancestor_id
 * @property string $message
 * @property-read User $author
 * @property-read Table $table
 * @property-read TableComment|null $ancestor
 * @property-read TableComment[]|Collection $replies
 */
class TableComment extends BaseModel
{
    use Reportable;
    protected $guarded = [];

    protected $touches = ['table'];

    protected static function boot()
    {
        parent::boot();

        static::deleting(function(TableComment $self) {
            $self->reportsOf()->delete();
        });
    }

    /** Context data table */
    public function table()
    {
        return $this->belongsTo(Table::class);
    }

    /** Parent comment (that we reply to; can be null) */
    public function ancestor()
    {
        return $this->belongsTo(TableComment::class, 'ancestor_id');
    }

    /** Replies to this comment */
    public function replies()
    {
        return $this->hasMany(TableComment::class, 'ancestor_id');
    }

    /** Authoring user */
    public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }
}