import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import { db } from "@/lib/db";
import { getPrivateFileByName } from "@/utils/backblaze";

export const GET = async (request: NextRequest) => {
    try {
        const session = await getServerSession(authOptions);

        if (!session || !session.user) {
            return new Response("Unauthorized", { status: 401 });
        }

        const user = await db.user.findUnique({
            where: {
                uuid: session?.user?.uuid || "",
            },
            include: {
                profile: {
                    include: {
                        picture: true,
                    },
                },
            }
        })
        if (!user) {
            return new Response("User not found", { status: 404 });
        }

        if (!user.profile?.picture?.file_name || !user.profile.picture.file_id) {
            return NextResponse.json({ picUrl: "/user.png" }, { status: 200 });
        }

        const picUrl = await getPrivateFileByName(
            user?.profile?.picture?.file_name as string
        )

        return NextResponse.json({picUrl: picUrl}, {status: 200})


    }
    catch (error: any) {
        return new Response("Internal Server Error", { status: 500 });
    }
}