import { getServerSession } from "api/auth/[...nextauth]/auth";
import { ROOMS } from "_data/livekitRooms";
import { AccessToken } from "livekit-server-sdk";
import { NextRequest } from "next/server";
import { getPublicUser, prisma } from "@repo/db";

/* if (!process.env.LIVEKIT_API_KEY) throw new Error("LIVEKIT_API_KEY not set");
if (!process.env.LIVEKIT_API_SECRET)
	throw new Error("LIVEKIT_API_SECRET not set"); */

export const GET = async (request: NextRequest) => {
	const roomName = request.nextUrl.searchParams.get("roomName");

	if (!roomName) return Response.json({ message: "Missing roomName" }, { status: 400 });

	const session = await getServerSession();

	if (!session) return Response.json({ message: "Unauthorized" }, { status: 401 });
	const user = await prisma.user.findUnique({
		where: {
			id: session.user.id,
		},
	});

	if (!user || !user.permissions.includes("AUDIO"))
		return Response.json({ message: "Missing permissions" }, { status: 401 });

	const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {
		identity: user.publicId,
		ttl: "1h",
	});

	at.addGrant({
		room: roomName,
		roomJoin: true,
		canPublish: true,
		canSubscribe: true,
		canUpdateOwnMetadata: true,
	});

	at.attributes = {
		publicId: user.publicId,
		publicUser: JSON.stringify(getPublicUser(user)),
		userId: user.id,
	};

	const token = await at.toJwt();

	return Response.json({ token });
};
