import { prisma } from "@repo/db";
import { RoomManager } from "_helpers/LivekitRoomManager";
import { getServerSession } from "api/auth/[...nextauth]/auth";
import { NextRequest } from "next/server";

export const GET = async (request: NextRequest) => {
	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_ADMIN"))
		return Response.json({ message: "Missing permissions" }, { status: 401 });

	const rooms = await RoomManager.listRooms();

	const roomsWithParticipants = rooms.map(async (room) => {
		const participants = await RoomManager.listParticipants(room.name);
		return {
			room,
			participants,
		};
	});

	return Response.json(await Promise.all(roomsWithParticipants), { status: 200 });
};

export const DELETE = async (request: NextRequest) => {
	try {
		const identity = request.nextUrl.searchParams.get("identity");
		const roomName = request.nextUrl.searchParams.get("roomName");
		const ban = request.nextUrl.searchParams.get("ban");

		if (!identity) return Response.json({ message: "Missing User identity" }, { status: 400 });
		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_ADMIN"))
			return Response.json({ message: "Missing permissions" }, { status: 401 });

		if (ban && !user.permissions.includes("ADMIN_USER")) {
			return Response.json({ message: "Missing permissions to ban user" }, { status: 401 });
		}

		if (ban) {
			const participant = await RoomManager.getParticipant(roomName, identity);
			const pUser = await prisma.user.findUnique({
				where: {
					id: participant.attributes.userId,
				},
			});
			if (!pUser) return;
			// If the user is banned, we need to remove their permissions
			await prisma.user.update({
				where: { id: session.user.id },
				data: {
					permissions: {
						set: pUser.permissions.filter((p) => p !== "AUDIO"),
					},
				},
			});
		}

		await RoomManager.removeParticipant(roomName, identity);
		return Response.json(
			{ message: `User ${identity} kicked from room ${roomName}` },
			{ status: 200 },
		);
	} catch (error) {
		console.error("Error in DELETE /api/livekit-participant:", error);
		return Response.json({ message: "Internal Server Error" }, { status: 500 });
	}
};
