<?php

namespace App\Services\Meet;

use App\Models\Participant;
use App\Models\QaQuestion;
use App\Models\Room;
use App\Models\Session;
use App\Models\User;
use App\Models\WebinarRegistration;

class WebinarService
{
    public function register(Room $room, string $email, string $displayName, array $metadata = []): WebinarRegistration
    {
        abort_unless($room->type === 'webinar', 422, 'Not a webinar room.');

        $autoApprove = $room->setting('webinar_auto_approve', false);

        return WebinarRegistration::updateOrCreate(
            ['room_id' => $room->id, 'email' => $email],
            [
                'owner_ref' => $room->owner_ref,
                'display_name' => $displayName,
                'status' => $autoApprove ? 'approved' : 'pending',
                'approved_at' => $autoApprove ? now() : null,
                'metadata' => $metadata,
            ],
        );
    }

    public function approve(WebinarRegistration $registration, User $host): WebinarRegistration
    {
        $registration->update(['status' => 'approved', 'approved_at' => now()]);

        return $registration->fresh();
    }

    public function reject(WebinarRegistration $registration): WebinarRegistration
    {
        $registration->update(['status' => 'rejected']);

        return $registration->fresh();
    }

    public function findApprovedRegistration(Room $room, string $email): ?WebinarRegistration
    {
        return WebinarRegistration::where('room_id', $room->id)
            ->where('email', $email)
            ->where('status', 'approved')
            ->first();
    }

    public function findByAccessToken(string $token): ?WebinarRegistration
    {
        return WebinarRegistration::where('access_token', $token)->where('status', 'approved')->first();
    }

    public function isWebinarAttendee(Room $room, Participant $participant): bool
    {
        return $room->type === 'webinar' && $participant->role === 'attendee';
    }

    public function canPublish(Room $room, Participant $participant): bool
    {
        if (! in_array($room->type, ['webinar', 'town_hall'], true)) {
            return true;
        }

        if (in_array($participant->role, ['host', 'co_host', 'panelist'], true)) {
            return true;
        }

        return (bool) $participant->speak_granted;
    }
}
