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

export async function POST(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser || (currentUser.role !== "super_admin" && currentUser.role !== "admin")) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
        }

        const body = await request.json();
        const { userIds, action } = body;

        if (!Array.isArray(userIds) || userIds.length === 0) {
            return NextResponse.json({ error: "No users selected" }, { status: 400 });
        }

        if (!["suspend", "unsuspend", "verify", "delete"].includes(action)) {
            return NextResponse.json({ error: "Invalid action" }, { status: 400 });
        }

        // Implementation of the Error Handling "Result Aggregation" Skill
        const results = {
            success: [] as string[],
            failed: [] as { id: string; reason: string }[]
        };

        // Process sequentially to handle errors per-user (for example, we can't delete users with active jobs via raw cascade if there's business logic, but here we'll use Prisma operations)
        for (const userId of userIds) {
            try {
                // Prevent self-action using the current session user ID
                if (userId === currentUser.id) {
                    results.failed.push({ id: userId, reason: "Cannot perform bulk actions on yourself" });
                    continue;
                }

                const targetUser = await prisma.user.findUnique({ where: { id: userId } });
                if (!targetUser) {
                    results.failed.push({ id: userId, reason: "User not found" });
                    continue;
                }

                // Prevent modifying other super_admins unless you are one
                if (targetUser.role === "super_admin" && currentUser.role !== "super_admin") {
                    results.failed.push({ id: userId, reason: "Insufficient permissions to modify super_admin" });
                    continue;
                }

                let details = {};

                if (action === "suspend") {
                    await prisma.$transaction([
                        prisma.user.update({
                            where: { id: userId },
                            data: { is_active: false }
                        }),
                        // Revoke active admin sessions if any
                        prisma.adminSession.updateMany({
                            where: { user_id: userId, status: "active" },
                            data: { status: "revoked" }
                        })
                    ]);
                    details = { previousState: targetUser.is_active, newState: false };
                }
                else if (action === "unsuspend") {
                    await prisma.user.update({
                        where: { id: userId },
                        data: { is_active: true }
                    });
                    details = { previousState: targetUser.is_active, newState: true };
                }
                else if (action === "verify") {
                    if (targetUser.role !== "employer") {
                        results.failed.push({ id: userId, reason: "Only employers require verification" });
                        continue;
                    }
                    await prisma.user.update({
                        where: { id: userId },
                        data: { email_verified: new Date() }
                    });
                    details = { previousState: targetUser.email_verified, newState: 'verified' };
                }
                else if (action === "delete") {
                    // Soft delete
                    await prisma.user.update({ 
                        where: { id: userId },
                        data: { deleted_at: new Date(), is_active: false }
                    });
                    details = { action: "soft_delete" };
                }

                // Log the audit event for this specific user
                await prisma.auditLog.create({
                    data: {
                        user_id: currentUser.id,
                        action: `user.bulk_${action}`,
                        resource_type: "user",
                        resource_id: userId,
                        details: details,
                        ip_address: request.headers.get("x-forwarded-for") || "unknown",
                        user_agent: request.headers.get("user-agent") || "unknown"
                    }
                });

                results.success.push(userId);
            } catch (err: any) {
                console.error(`Bulk action ${action} failed for user ${userId}:`, err);
                results.failed.push({ id: userId, reason: err.message || "Internal database error" });
            }
        }

        return NextResponse.json({
            message: `Bulk action '${action}' completed. ${results.success.length} succeeded, ${results.failed.length} failed.`,
            results
        });

    } catch (error) {
        console.error("Bulk Action Error:", error);
        return NextResponse.json({ error: "Failed to process bulk actions" }, { status: 500 });
    }
}
