<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Models\BreakoutRoom;
use App\Models\MeetPoll;
use App\Models\QaQuestion;
use App\Models\Room;
use App\Models\Session;
use App\Models\SessionFile;
use App\Models\Whiteboard;
use App\Services\Meet\BreakoutService;
use App\Services\Meet\FileSharingService;
use App\Services\Meet\PollService;
use App\Services\Meet\QaService;
use App\Services\Meet\WebinarService;
use App\Services\Meet\WhiteboardService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

class WebinarRegistrationController extends Controller
{
    public function __construct(
        protected WebinarService $webinars,
    ) {}

    public function show(Room $room): View
    {
        abort_unless($room->isWebinar(), 404);

        return view('meet.webinar.register', compact('room'));
    }

    public function store(Request $request, Room $room): View
    {
        abort_unless($room->isWebinar(), 404);

        $validated = $request->validate([
            'email' => ['required', 'email'],
            'display_name' => ['required', 'string', 'max:100'],
        ]);

        $registration = $this->webinars->register(
            $room,
            $validated['email'],
            $validated['display_name'],
        );

        return view('meet.webinar.register-done', compact('room', 'registration'));
    }

    public function manage(Request $request, Room $room): View
    {
        $this->authorizeWebinarHost($request, $room);

        $registrations = $room->webinarRegistrations()->orderByDesc('created_at')->get();

        return view('meet.webinar.registrations', compact('room', 'registrations'));
    }

    public function approve(Request $request, Room $room, \App\Models\WebinarRegistration $registration): RedirectResponse
    {
        $this->authorizeWebinarHost($request, $room);
        abort_unless($registration->room_id === $room->id, 404);

        $this->webinars->approve($registration, $request->user());

        return back()->with('success', 'Registration approved.');
    }

    public function reject(Request $request, Room $room, \App\Models\WebinarRegistration $registration): RedirectResponse
    {
        $this->authorizeWebinarHost($request, $room);
        abort_unless($registration->room_id === $room->id, 404);

        $this->webinars->reject($registration);

        return back()->with('success', 'Registration rejected.');
    }

    protected function authorizeWebinarHost(Request $request, Room $room): void
    {
        abort_unless($request->user()?->ownerRef() === $room->host_user_ref, 403);
    }
}
