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

export async function GET(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const currentUser = await getCurrentUser();
        // Only super_admin or admin can view user details
        if (!currentUser || (currentUser.role !== "super_admin" && currentUser.role !== "admin")) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
        }

        const { id: userId } = await params;

        const user = await prisma.user.findUnique({
            where: { id: userId },
            include: {
                profile: true,
                skills: {
                    include: {
                        skill: true
                    }
                },
                experiences: {
                    orderBy: { start_date: 'desc' }
                },
                education: {
                    orderBy: { start_date: 'desc' }
                },
                // Include employer stats if they are an employer
                jobs: {
                    take: 10,
                    orderBy: { posted_at: 'desc' },
                    select: {
                        id: true,
                        title: true,
                        status: true,
                        posted_at: true,
                        applicant_count: true,
                        work_location_type: true
                    }
                },
                // Include candidate stats if they are a candidate
                applications: {
                    take: 10,
                    orderBy: { applied_at: 'desc' },
                    include: {
                        job: {
                            select: { title: true, company: true }
                        }
                    }
                },
                _count: {
                    select: {
                        jobs: true,
                        applications: true,
                        audit_logs: true
                    }
                }
            }
        });

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

        // Return a sanitized version without password hash
        const { password_hash, ...safeUser } = user;

        return NextResponse.json(safeUser);
    } catch (error) {
        console.error("User Detail Fetch Error:", error);
        return NextResponse.json({ error: "Failed to fetch user details" }, { status: 500 });
    }
}
