import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@repo/db";
import { getServerSession } from "../../auth/[...nextauth]/auth";

// DELETE /api/booking/[id] - Delete a booking
export const DELETE = async (req: NextRequest, { params }: { params: { id: string } }) => {
	try {
		console.log(params);
		const session = await getServerSession();
		if (!session?.user) {
			return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
		}

		const bookingId = params.id;

		// Find the booking
		const booking = await prisma.booking.findUnique({
			where: { id: bookingId },
		});

		if (!booking) {
			return NextResponse.json({ error: "Booking not found" }, { status: 404 });
		}

		// Check if user owns the booking or has admin permissions
		if (booking.userId !== session.user.id && !session.user.permissions.includes("ADMIN_KICK")) {
			return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
		}

		// Delete the booking
		await prisma.booking.delete({
			where: { id: bookingId },
		});

		return NextResponse.json({ success: true });
	} catch (error) {
		console.error("Error deleting booking:", error);
		return NextResponse.json({ error: "Internal server error" }, { status: 500 });
	}
};

// PUT /api/booking/[id] - Update a booking
export const PUT = async (req: NextRequest, { params }: { params: { id: string } }) => {
	try {
		const session = await getServerSession();
		if (!session?.user) {
			return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
		}

		const bookingId = params.id;
		const body = await req.json();
		const { type, stationId, startTime, endTime } = body;

		// Find the booking
		const existingBooking = await prisma.booking.findUnique({
			where: { id: bookingId },
		});

		if (!existingBooking) {
			return NextResponse.json({ error: "Booking not found" }, { status: 404 });
		}

		// Check if user owns the booking or has admin permissions
		if (
			existingBooking.userId !== session.user.id &&
			!session.user.permissions.includes("ADMIN_KICK")
		) {
			return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
		}

		// Validate permissions for LST bookings
		const lstTypes = ["LST_01", "LST_02", "LST_03", "LST_04"];
		if (lstTypes.includes(type)) {
			if (!session.user.permissions.includes("DISPO")) {
				return NextResponse.json(
					{ error: "Insufficient permissions for LST booking" },
					{ status: 403 },
				);
			}
		}

		// Check for conflicts (excluding current booking)
		const conflictWhere = {
			id: { not: bookingId },
			type,
			OR: [
				{
					startTime: {
						lt: new Date(endTime),
					},
					endTime: {
						gt: new Date(startTime),
					},
				},
			],
			...(type === "STATION" && stationId ? { stationId } : {}),
		};

		const conflictingBooking = await prisma.booking.findFirst({
			where: conflictWhere,
		});

		if (conflictingBooking) {
			const resourceName = type === "STATION" ? `Station` : type;
			return NextResponse.json(
				{ error: `Konflikt erkannt: ${resourceName} ist bereits für diesen Zeitraum gebucht.` },
				{ status: 409 },
			);
		}

		// Update the booking
		const updatedBooking = await prisma.booking.update({
			where: { id: bookingId },
			data: {
				type,
				stationId: type === "STATION" ? stationId : null,
				startTime: new Date(startTime),
				endTime: new Date(endTime),
			},
			include: {
				User: true,
				Station: {
					select: {
						id: true,
						bosCallsignShort: true,
					},
				},
			},
		});

		return NextResponse.json({ booking: updatedBooking });
	} catch (error) {
		console.error("Error updating booking:", error);
		return NextResponse.json({ error: "Internal server error" }, { status: 500 });
	}
};
