<?php

namespace App\Actions\V1\Project;

use App\Dto\V1\Project\ProjectLikeDto;
use App\Exceptions\ProjectLikeException;
use App\Models\Project;
use App\Repositories\V1\Projects\ProjectLikeRepositoryInterface;
use App\Repositories\V1\Projects\ProjectRepositoryInterface;

readonly class ToggleProjectLikeAction
{
    public function __construct(
        private ProjectLikeRepositoryInterface $projectLikeRepository,
        private ProjectRepositoryInterface $projectRepository
    )
    {
    }

    /**
     * @throws ProjectLikeException
     */
    public function execute(ProjectLikeDto $dto): int
    {
        $project = $this->projectRepository->findById($dto->projectId);
        if (!$project) {
            throw new ProjectLikeException(message: __('exceptions.project_not_found'));
        }

        if ($this->projectLikeRepository->findByUserAndProject($dto->userId, $dto->projectId)) {
            $this->projectLikeRepository->delete($dto->userId, $dto->projectId);
        } else {
            $this->projectLikeRepository->create([
                'user_id' => $dto->userId,
                'project_id' => $dto->projectId
            ]);
        }

        return $this->projectLikeRepository->countByProject($dto->projectId);
    }
}