import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export async function GET(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const user = await prisma.user.findUnique({
            where: { id: currentUser.id },
            include: {
                profile: true,
                skills: {
                    include: { skill: true }
                },
                experiences: { orderBy: { start_date: 'desc' } },
                education: { orderBy: { start_date: 'desc' } },
                certifications: { orderBy: { issue_date: 'desc' } },
                projects: { orderBy: { start_date: 'desc' } },
                awards: { orderBy: { date: 'desc' } },
                languages: true,
                publications: { orderBy: { date: 'desc' } },
                volunteer_experiences: { orderBy: { start_date: 'desc' } }
            }
        });

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

        return NextResponse.json(user);
    } catch (error) {
        console.error("Fetch Profile Error:", error);
        return NextResponse.json({ error: "Failed to fetch profile" }, { status: 500 });
    }
}

export async function PUT(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const body = await request.json();

        // This endpoint acts as a partial updater for the User and their base Profile.
        // It separates standard user fields from profile fields.
        const {
            first_name,
            last_name,
            avatar_url,
            phone,
            location,
            headline,
            about_me,
            ...otherProfileFields
        } = body;

        // Perform an interactive transaction to update both User and Profile atomically
        const updatedUser = await prisma.$transaction(async (tx) => {
            // Update User Base
            const u = await tx.user.update({
                where: { id: currentUser.id },
                data: {
                    ...(first_name !== undefined && { first_name }),
                    ...(last_name !== undefined && { last_name }),
                    ...(avatar_url !== undefined && { avatar_url }),
                    // Automatically construct full name based on first and last
                    ...(first_name && last_name && { name: `${first_name} ${last_name}` })
                }
            });

            // Update or Create Profile Base
            const profileData = {
                ...(headline !== undefined && { headline }),
                ...(about_me !== undefined && { about_me }),
                ...(location !== undefined && { location }),
                ...(phone !== undefined && { phone }),
                ...otherProfileFields
            };

            if (Object.keys(profileData).length > 0) {
                await tx.profile.upsert({
                    where: { user_id: currentUser.id },
                    update: profileData,
                    create: {
                        user_id: currentUser.id,
                        ...profileData
                    }
                });
            }

            return u;
        });

        return NextResponse.json({ message: "Profile updated successfully", user: updatedUser });
    } catch (error) {
        console.error("Update Profile Error:", error);
        return NextResponse.json({ error: "Failed to update profile" }, { status: 500 });
    }
}
