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

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

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

        // Parse filters
        const search = searchParams.get('search') || '';
        const role = searchParams.get('role');
        const status = searchParams.get('status');
        const joinFrom = searchParams.get('joinFrom');

        // Build the where clause
        const where: Prisma.UserWhereInput = {};

        if (search) {
            where.OR = [
                { name: { contains: search, mode: 'insensitive' } },
                { email: { contains: search, mode: 'insensitive' } },
            ];
        }

        if (role) {
            where.role = role;
        }

        if (status) {
            if (status === "active") where.is_active = true;
            if (status === "suspended") where.is_active = false;
            // For pending, we might look at email_verified or a specific profile state
        }

        if (joinFrom) {
            where.created_at = {
                gte: new Date(joinFrom)
            };
        }

        // Use Web Streams API to progressively yield CSV rows and avoid OOM
        const stream = new ReadableStream({
            async start(controller) {
                const headers = [
                    "ID", "Name", "Email", "Role", "Status", "Joined Date",
                    "Email Verified", "Jobs Posted", "Applications Submitted",
                    "Location", "Phone"
                ];
                controller.enqueue(headers.join(',') + '\n');

                const batchSize = 1000;
                let skip = 0;
                let hasMore = true;

                while (hasMore) {
                    const users = await prisma.user.findMany({
                        where,
                        include: {
                            profile: true,
                            _count: {
                                select: { jobs: true, applications: true }
                            }
                        },
                        orderBy: { created_at: 'desc' },
                        take: batchSize,
                        skip: skip
                    });

                    if (users.length === 0) {
                        hasMore = false;
                        break;
                    }

                    const csvRows = users.map(user => {
                        return [
                            user.id,
                            `"${user.name.replace(/"/g, '""')}"`, // Escape quotes
                            user.email,
                            user.role,
                            user.is_active ? "Active" : "Suspended",
                            user.created_at.toISOString().split('T')[0],
                            user.email_verified ? "Yes" : "No",
                            user._count.jobs,
                            user._count.applications,
                            `"${user.profile?.location?.replace(/"/g, '""') || ''}"`,
                            user.profile?.phone || ''
                        ].join(',');
                    });

                    controller.enqueue(csvRows.join('\n') + '\n');
                    skip += batchSize;
                }

                controller.close();
            }
        });

        // Return as a downloadable streaming file
        return new NextResponse(stream, {
            status: 200,
            headers: {
                'Content-Type': 'text/csv; charset=utf-8',
                'Content-Disposition': `attachment; filename="jobzio_users_export_${new Date().toISOString().split('T')[0]}.csv"`,
            }
        });

    } catch (error) {
        console.error("Export Action Error:", error);
        return NextResponse.json({ error: "Failed to export users" }, { status: 500 });
    }
}
