import { cookies } from "next/headers";

export const GET = async (req) => {
    const cookie = await cookies();
    const token = cookie.get("token")?.value;

    if (!token) {
        return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
    }

    try {

        const { searchParams } = req.nextUrl;
        const doctorId = searchParams.get("doctorId");
        console.log("Doctor ID:", doctorId);

        const backendUrl = new URL(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/patients`);
        if (doctorId) {
            backendUrl.searchParams.set("doctorId", doctorId);
        }

        const response = await fetch(backendUrl.toString(), {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                cookie: req.headers.get("cookie") || "",
            },
        });

        if (!response.ok) {
            throw new Error("Failed to fetch patients");
        }

        const data = await response.json();
        return new Response(JSON.stringify(data), { status: 200 });
    } catch (error) {
        console.error("Error fetching patients:", error);
        return new Response(JSON.stringify({ error: "Internal server error" }), { status: 500 });
    }
};
