<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    protected $fillable = ['post_id', 'user_id', 'content', 'parent_id'];

    protected $with = ['user']; // Always load author

    public function user()
    {
        return $this->belongsTo(User::class)->select(['id', 'name', 'username', 'avatar']);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    // Parent Comment
    public function parent()
    {
        return $this->belongsTo(Comment::class, 'parent_id');
    }

    // Replies (Recursive Loading for Sub-comments)
    public function children()
    {
        // Added 'children' to automatically load replies of replies
        return $this->hasMany(Comment::class, 'parent_id')->with(['user', 'children']); 
    }
}