<?php

namespace App\Services\Integrations;

use App\Models\Room;
use App\Models\User;
use App\Support\EventsSourceLink;

class EventsLinkService
{
    public function __construct(private readonly EventsClient $events) {}

    /**
     * @return list<array<string, mixed>>
     */
    public function linkableEvents(User $user): array
    {
        if (! $this->events->isConfigured()) {
            return [];
        }

        return $this->events->linkableEvents($user->ownerRef());
    }

    public function link(Room $room, User $user, int $eventId, ?string $virtualSessionId = null): Room
    {
        abort_unless($room->isWebinar() || $room->isConference(), 422);

        $result = $this->events->linkRoom($eventId, [
            'owner_ref' => $user->ownerRef(),
            'meet_room_uuid' => $room->uuid,
            'meet_room_type' => $room->isConference() ? 'town_hall' : 'webinar',
            'join_url' => $room->joinUrl(),
            'title' => $room->title,
            'scheduled_at' => $room->scheduled_at?->toIso8601String(),
            'duration_minutes' => $room->duration_minutes ?? 60,
            'virtual_session_id' => $virtualSessionId,
        ]);

        $room->update([
            'source' => [
                'app' => 'events',
                'entity_type' => 'virtual_session',
                'entity_id' => (string) ($result['entity_id'] ?? ''),
                'event_id' => (string) $eventId,
                'event_title' => (string) ($result['title'] ?? ''),
                'registration_url' => (string) ($result['registration_url'] ?? ''),
                'short_code' => (string) ($result['short_code'] ?? ''),
            ],
        ]);

        return $room->fresh();
    }

    public function unlink(Room $room): Room
    {
        abort_unless(EventsSourceLink::isLinked($room), 422);

        $room->update(['source' => null]);

        return $room->fresh();
    }
}
