<?php

namespace App\Services\Meet\Media;

use Agence104\LiveKit\AccessToken;
use Agence104\LiveKit\AccessTokenOptions;
use Agence104\LiveKit\VideoGrant;

class LiveKitProvider implements MediaProviderInterface
{
    public function createRoom(string $roomName, array $options = []): void
    {
        // LiveKit creates rooms lazily on first join.
    }

    public function deleteRoom(string $roomName): void
    {
        //
    }

    public function generateToken(
        string $roomName,
        string $identity,
        string $displayName,
        array $grants = [],
    ): string {
        $apiKey = (string) config('meet.media.livekit.api_key');
        $apiSecret = (string) config('meet.media.livekit.api_secret');

        $tokenOptions = (new AccessTokenOptions())
            ->setIdentity($identity)
            ->setName($displayName)
            ->setTtl(3600);

        $videoGrant = (new VideoGrant())
            ->setRoomJoin()
            ->setRoomName($roomName)
            ->setCanPublish($grants['can_publish'] ?? true)
            ->setCanSubscribe($grants['can_subscribe'] ?? true)
            ->setCanPublishData($grants['can_publish_data'] ?? true);

        if ($grants['room_admin'] ?? false) {
            $videoGrant->setRoomAdmin();
        }

        return (new AccessToken($apiKey, $apiSecret))
            ->init($tokenOptions)
            ->setGrant($videoGrant)
            ->toJwt();
    }

    public function isConfigured(): bool
    {
        return filled(config('meet.media.livekit.url'))
            && filled(config('meet.media.livekit.api_key'))
            && filled(config('meet.media.livekit.api_secret'));
    }

    public function serverUrl(): string
    {
        return (string) config('meet.media.livekit.url');
    }
}
