<?php

namespace App\Services;

use App\Interfaces\PollRepositoryInterface;
use App\Models\User;
use Illuminate\Http\Exceptions\HttpResponseException;

class PollService
{
    public function __construct(
        private readonly PollRepositoryInterface $pollRepository,
        private readonly PointService $pointService
    ) {}

    public function vote(User $user, int $pollId, int $optionIndex): array
    {
        $poll = $this->pollRepository->findById($pollId);

        if (! $poll) {
            $this->abort(404, 'Poll not found.');
        }

        if (! $poll->is_active) {
            $this->abort(422, 'This poll is no longer active.');
        }

        if ($this->pollRepository->hasVoted($user->id, $pollId)) {
            $this->abort(422, 'You have already voted in this poll.');
        }

        if ($optionIndex < 0 || $optionIndex >= count($poll->options)) {
            $this->abort(422, 'Invalid option selected.');
        }

        $vote = $this->pollRepository->vote($user->id, $pollId, $optionIndex);

        // Award points for poll participation
        $this->pointService->awardForReason($user, 'poll_vote', $vote);

        $results = $this->pollRepository->getVoteResults($pollId);

        return [
            'vote'    => $vote,
            'results' => $results,
        ];
    }

    private function abort(int $status, string $message): never
    {
        throw new HttpResponseException(
            response()->json(['message' => $message], $status)
        );
    }
}
