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 viw user activity
        if (!currentUser || (currentUser.role !== "super_admin" && currentUser.role !== "admin")) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
        }

        const { id: userId } = await params;
        const { searchParams } = new URL(request.url);
        const page = parseInt(searchParams.get("page") || "1");
        const limit = parseInt(searchParams.get("limit") || "50");
        const skip = (page - 1) * limit;

        // Fetch chronological audit logs for this specific user
        const [activities, totalCount] = await Promise.all([
            prisma.auditLog.findMany({
                where: { user_id: userId },
                orderBy: { created_at: 'desc' },
                skip,
                take: limit
            }),
            prisma.auditLog.count({ where: { user_id: userId } })
        ]);

        return NextResponse.json({
            activities,
            pagination: {
                total: totalCount,
                page,
                limit,
                totalPages: Math.ceil(totalCount / limit)
            }
        });
    } catch (error) {
        console.error("User Activity Fetch Error:", error);
        return NextResponse.json({ error: "Failed to fetch user activity" }, { status: 500 });
    }
}
