<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Models\Room;
use App\Services\Meet\WebinarService;
use App\Support\EventsSourceLink;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

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

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

        return $this->redirectToEvents($room);
    }

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

        return $this->redirectToEvents($room);
    }

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

        return $this->redirectToEventsAdmin($room);
    }

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

        return $this->redirectToEventsAdmin($room);
    }

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

        return $this->redirectToEventsAdmin($room);
    }

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

    protected function redirectToEvents(Room $room): RedirectResponse
    {
        $url = EventsSourceLink::eventRegistrationUrl($room);

        if ($url) {
            return redirect()->away($url);
        }

        return redirect()
            ->route('meet.webinars.show', $room)
            ->withErrors(['register' => 'Link this webinar to Ladill Events to enable registration.']);
    }

    protected function redirectToEventsAdmin(Room $room): RedirectResponse
    {
        $url = EventsSourceLink::eventAdminUrl($room);

        if ($url) {
            return redirect()->away($url);
        }

        return redirect()
            ->route('meet.webinars.show', $room)
            ->withErrors(['register' => 'Link this webinar to Ladill Events to manage registrations.']);
    }
}
