<?php

namespace App\Repositories\V1\Projects;

use App\Exceptions\InvalidParentCommentException;
use App\Models\ProjectComment;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;


class MysqlProjectCommentRepository implements ProjectCommentRepositoryInterface
{
    public function create(array $data): ProjectComment
    {
        return ProjectComment::create($data);
    }

    public function findOrFailMainComment(int $id): ProjectComment
    {
        $comment = ProjectComment::find($id);

        if (!$comment || $comment->isReply()) {
            throw new InvalidParentCommentException();
        }

        return $comment;
    }

    public function getTopLevelComments(int $projectId, int $limit): LengthAwarePaginator
    {
        return ProjectComment::with(['user', 'replies.user'])
            ->where('project_id', $projectId)
            ->whereNull('parent_id')
            ->latest()
            ->paginate($limit);
    }
}
