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

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

        const { searchParams } = new URL(request.url);
        const type = searchParams.get('type') || 'queue'; // 'queue' or 'logs'
        const page = parseInt(searchParams.get('page') || '1');
        const limit = parseInt(searchParams.get('limit') || '50');
        const skip = (page - 1) * limit;

        if (type === 'queue') {
            const [queue, total] = await Promise.all([
                prisma.emailQueue.findMany({
                    orderBy: { created_at: 'desc' },
                    skip,
                    take: limit,
                }),
                prisma.emailQueue.count()
            ]);
            return NextResponse.json({ data: queue, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } });
        } else {
            const [logs, total] = await Promise.all([
                prisma.emailLog.findMany({
                    orderBy: { sent_at: 'desc' },
                    skip,
                    take: limit,
                }),
                prisma.emailLog.count()
            ]);
            return NextResponse.json({ data: logs, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } });
        }
    } catch (error: any) {
        console.error("Error fetching emails:", error);
        return NextResponse.json({ error: "Internal server error" }, { status: 500 });
    }
}
