<?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 Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class EventsLinkController extends Controller
{
    use ScopesToAccount;

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

    public function show(Request $request, Room $room): 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.']);
        }

        return redirect()
            ->route($room->isWebinar() ? 'meet.webinars.show' : 'meet.conferences.show', $room)
            ->with('open_events_link_modal', true);
    }

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

        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'event_id' => ['required', 'integer', 'min:1'],
            'virtual_session_id' => ['nullable', 'string', 'max:64'],
        ]);

        if ($validator->fails()) {
            return redirect()
                ->route($room->isWebinar() ? 'meet.webinars.show' : 'meet.conferences.show', $room)
                ->withErrors($validator)
                ->withInput()
                ->with('open_events_link_modal', true);
        }

        $validated = $validator->validated();

        try {
            $this->links->link(
                $room,
                $request->user(),
                (int) $validated['event_id'],
                $validated['virtual_session_id'] ?? null,
            );
        } catch (\RuntimeException $e) {
            return redirect()
                ->route($room->isWebinar() ? 'meet.webinars.show' : 'meet.conferences.show', $room)
                ->withErrors(['events' => $e->getMessage()])
                ->withInput()
                ->with('open_events_link_modal', true);
        }

        $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.');
    }
}
