<?php

namespace ViartasCore\Comments\Traits;

use ViartasCore\Comments\Models\Comment;

trait HasComments
{
    /**
     * Get all comments for this model
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

    /**
     * Get only approved comments
     */
    public function approvedComments()
    {
        return $this->comments()->approved();
    }

    /**
     * Get root comments (no parent)
     */
    public function rootComments()
    {
        return $this->comments()->root();
    }

    /**
     * Get approved root comments with replies
     */
    public function approvedRootComments()
    {
        return $this->comments()
            ->approved()
            ->root()
            ->with(['allReplies' => function ($query) {
                $query->approved();
            }, 'user'])
            ->orderBy('created_at', 'desc');
    }

    /**
     * Get pending comments count
     */
    public function pendingCommentsCount()
    {
        return $this->comments()->pending()->count();
    }

    /**
     * Get average rating from comments
     */
    public function averageRating()
    {
        return $this->comments()
            ->approved()
            ->whereNotNull('rating')
            ->avg('rating');
    }

    /**
     * Get rating distribution
     */
    public function ratingDistribution()
    {
        $distribution = [];
        for ($i = 5; $i >= 1; $i--) {
            $distribution[$i] = $this->comments()
                ->approved()
                ->where('rating', $i)
                ->count();
        }
        return $distribution;
    }

    /**
     * Get comments count
     */
    public function commentsCount()
    {
        return $this->comments()->approved()->count();
    }
}
