<?php

namespace App\Services\Meet;

use App\Models\Participant;
use App\Models\QaQuestion;
use App\Models\Session;

class QaService
{
    public function submit(Session $session, Participant $participant, string $question): QaQuestion
    {
        return QaQuestion::create([
            'owner_ref' => $session->owner_ref,
            'session_id' => $session->id,
            'participant_uuid' => $participant->uuid,
            'asker_name' => $participant->display_name,
            'question' => $question,
            'status' => 'pending',
        ]);
    }

    public function approve(QaQuestion $question): QaQuestion
    {
        $question->update(['status' => 'approved']);

        return $question->fresh();
    }

    public function answer(QaQuestion $question, string $answer, string $answeredBy): QaQuestion
    {
        $question->update([
            'status' => 'answered',
            'answer' => $answer,
            'answered_by' => $answeredBy,
        ]);

        return $question->fresh();
    }

    public function dismiss(QaQuestion $question): QaQuestion
    {
        $question->update(['status' => 'dismissed']);

        return $question->fresh();
    }

    public function upvote(QaQuestion $question): QaQuestion
    {
        $question->increment('upvotes');

        return $question->fresh();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Collection<int, QaQuestion>
     */
    public function forSession(Session $session, bool $publicOnly = false)
    {
        $query = $session->qaQuestions()->orderByDesc('upvotes')->orderBy('created_at');

        if ($publicOnly) {
            $query->whereIn('status', ['approved', 'answered']);
        }

        return $query->get();
    }
}
