<?php

namespace App\Actions\V1\Project;

use App\Dto\V1\Project\ProjectCommentDto;
use App\Exceptions\WrongProjectReplyException;
use App\Models\ProjectComment;
use App\Repositories\V1\Projects\ProjectCommentRepositoryInterface;
use App\Repositories\V1\Projects\ProjectRepositoryInterface;

readonly class StoreProjectCommentAction
{
    public function __construct(
        private ProjectRepositoryInterface        $projectRepository,
        private ProjectCommentRepositoryInterface $projectCommentRepository,
    )
    {
    }

    public function execute(int $id, int $userId, ProjectCommentDto $dto): ProjectComment
    {
        $this->projectRepository->findOrFail($id);

        if ($dto->parentId) {
            $parentComment = $this->projectCommentRepository->findOrFailMainComment($dto->parentId);

            if ($parentComment->project_id !== $id) {
                throw new WrongProjectReplyException();
            }
        }

        return $this->projectCommentRepository->create($dto->storePayload($id, $userId));
    }
}
