<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\Room;
use App\Services\Integrations\EventsClient;
use App\Services\Integrations\EventsLinkService;
use App\Support\EventsSourceLink;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class EventsLinkController extends Controller
{
    use ScopesToAccount;

    public function __construct(
        protected EventsLinkService $links,
        protected EventsClient $eventsClient,
    ) {}

    public function show(Request $request, Room $room): View|RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.manage');
        $this->authorizeOwner($request, $room);
        abort_unless($room->isWebinar() || $room->isConference(), 404);

        if (! $this->eventsClient->isConfigured()) {
            return redirect()
                ->route($room->isWebinar() ? 'meet.webinars.show' : 'meet.conferences.show', $room)
                ->withErrors(['events' => 'Ladill Events linking is not configured. Set MEET_API_KEY_EVENTS in Meet (and the matching EVENTS_API_KEY_MEET in Events), then try again.']);
        }

        $events = $this->links->linkableEvents($request->user());
        $expectedType = $room->isConference() ? 'town_hall' : 'webinar';

        return view('meet.events.link', [
            'room' => $room,
            'events' => $events,
            'expectedType' => $expectedType,
            'eventsAppUrl' => EventsSourceLink::baseUrl(),
            'isLinked' => EventsSourceLink::isLinked($room),
        ]);
    }

    public function store(Request $request, Room $room): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.manage');
        $this->authorizeOwner($request, $room);
        abort_unless($room->isWebinar() || $room->isConference(), 404);

        $validated = $request->validate([
            'event_id' => ['required', 'integer', 'min:1'],
            'virtual_session_id' => ['nullable', 'string', 'max:64'],
        ]);

        try {
            $this->links->link(
                $room,
                $request->user(),
                (int) $validated['event_id'],
                $validated['virtual_session_id'] ?? null,
            );
        } catch (\RuntimeException $e) {
            return back()->withErrors(['events' => $e->getMessage()])->withInput();
        }

        $route = $room->isWebinar() ? 'meet.webinars.show' : 'meet.conferences.show';

        return redirect()->route($route, $room)->with('success', 'Linked to Ladill Events. Registration and invitations are now managed in Events.');
    }

    public function destroy(Request $request, Room $room): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.manage');
        $this->authorizeOwner($request, $room);

        $this->links->unlink($room);

        $route = $room->isWebinar() ? 'meet.webinars.show' : 'meet.conferences.show';

        return redirect()->route($route, $room)->with('success', 'Events link removed.');
    }
}
