<?php

namespace App\Services\Meet;

use App\Models\MeetPoll;
use App\Models\Participant;
use App\Models\PollVote;
use App\Models\Session;

class PollService
{
    /**
     * @param  array<int, string>  $options
     */
    public function create(Session $session, string $question, array $options): MeetPoll
    {
        return MeetPoll::create([
            'owner_ref' => $session->owner_ref,
            'session_id' => $session->id,
            'question' => $question,
            'options' => array_values($options),
            'status' => 'open',
        ]);
    }

    public function vote(MeetPoll $poll, Participant $participant, int $optionIndex): PollVote
    {
        abort_unless($poll->status === 'open', 422);
        abort_unless(isset($poll->options[$optionIndex]), 422);

        return PollVote::updateOrCreate(
            ['poll_id' => $poll->id, 'participant_uuid' => $participant->uuid],
            ['option_index' => $optionIndex],
        );
    }

    public function close(MeetPoll $poll): MeetPoll
    {
        $poll->update(['status' => 'closed']);

        return $poll->fresh();
    }

    /**
     * @return array<string, mixed>
     */
    public function results(MeetPoll $poll): array
    {
        $counts = array_fill(0, count($poll->options ?? []), 0);
        foreach ($poll->votes as $vote) {
            $counts[$vote->option_index] = ($counts[$vote->option_index] ?? 0) + 1;
        }

        return [
            'poll' => $poll,
            'counts' => $counts,
            'total_votes' => $poll->votes()->count(),
        ];
    }
}
