import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { hashPassword } from "@/lib/password";
import { UserRole } from "@/lib/permissions";
import { randomBytes } from "crypto";

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

        const { searchParams } = new URL(request.url);

        // Pagination
        const page = parseInt(searchParams.get("page") || "1");
        const limit = parseInt(searchParams.get("limit") || "50");
        const skip = (page - 1) * limit;

        // Filters
        const search = searchParams.get("search") || "";
        const rolesParam = searchParams.get("roles"); // e.g., "candidate,employer"
        const statusParam = searchParams.get("status"); // "active", "suspended", "all"

        // Build the query
        const whereClause: any = {};

        if (search) {
            whereClause.OR = [
                { name: { contains: search, mode: 'insensitive' } },
                { email: { contains: search, mode: 'insensitive' } },
                { id: { contains: search, mode: 'insensitive' } } // Can search by UUID
            ];
        }

        if (rolesParam) {
            whereClause.role = { in: rolesParam.split(',') };
        }

        if (statusParam && statusParam !== "all") {
            if (statusParam === "active") whereClause.is_active = true;
            if (statusParam === "suspended") whereClause.is_active = false;
        }

        // Execute query & count in parallel
        const [users, totalCount] = await Promise.all([
            prisma.user.findMany({
                where: whereClause,
                select: {
                    id: true,
                    name: true,
                    email: true,
                    role: true,
                    is_active: true,
                    department: true,
                    created_at: true,
                    last_login_at: true,
                    email_verified: true,
                    avatar_url: true,
                    _count: {
                        select: {
                            jobs: true,          // Employer metric
                            applications: true   // Candidate metric
                        }
                    }
                },
                orderBy: { created_at: 'desc' },
                skip,
                take: limit,
            }),
            prisma.user.count({ where: whereClause })
        ]);

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

export async function POST(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        // Only super_admin can create new admins
        if (!currentUser || currentUser.role !== "super_admin") {
            return NextResponse.json({ error: "Unauthorized - Super Admin only" }, { status: 403 });
        }

        const { name, email, role, department } = await request.json();

        if (!name || !email || !role) {
            return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
        }

        // Validate role
        const validRoles: UserRole[] = ["super_admin", "admin", "moderator", "analyst", "support"];
        if (!validRoles.includes(role)) {
            return NextResponse.json({ error: "Invalid admin role" }, { status: 400 });
        }

        // Generate a secure temporary password
        const tempPassword = randomBytes(12).toString("base64");
        const hashedPassword = await hashPassword(tempPassword);

        // Create user in DB using Prisma
        const existingUser = await prisma.user.findUnique({ where: { email } });

        if (existingUser) {
            return NextResponse.json({ error: "Email already exists" }, { status: 400 });
        }

        const newUser = await prisma.user.create({
            data: {
                name,
                email,
                password_hash: hashedPassword,
                role: role,
                department: department || null,
                is_active: true,
                email_verified: new Date()
            }
        });

        // In a real app, send email with temp password here.
        console.log(`[SECURE] Admin created. Temp password for ${email}: ${tempPassword}`);

        return NextResponse.json({
            message: "Admin created successfully",
            adminId: newUser.id
        });

    } catch (error) {
        console.error("Admin Creation Error:", error);
        return NextResponse.json({ error: "Failed to create admin" }, { status: 500 });
    }
}
