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

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

        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const [
            pendingCount,
            urgentCount,
            recentCount,
            approvedTodayCount,
            rejectedTodayCount
        ] = await Promise.all([
            // Total Pending (Awaiting Review)
            prisma.job.count({ where: { status: 'pending' } }),

            // Urgent Pending (> 24 hours ago)
            prisma.job.count({
                where: {
                    status: 'pending',
                    posted_at: { lt: new Date(Date.now() - 24 * 60 * 60 * 1000) }
                }
            }),

            // Recent Pending (< 24 hours ago)
            prisma.job.count({
                where: {
                    status: 'pending',
                    posted_at: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }
                }
            }),

            // Approved Today via AuditLogs
            prisma.auditLog.count({
                where: {
                    action: 'job.approved',
                    created_at: { gte: today }
                }
            }),

            // Rejected Today via AuditLogs
            prisma.auditLog.count({
                where: {
                    action: 'job.rejected',
                    created_at: { gte: today }
                }
            })
        ]);

        return NextResponse.json({
            pending: pendingCount,
            urgent: urgentCount,
            recent: recentCount,
            approvedToday: approvedTodayCount,
            rejectedToday: rejectedTodayCount,
            // Mock static times for the MVP, the AI is planned for later phases
            averageReviewTimeMinutes: 15
        });

    } catch (error: any) {
        console.error("Error fetching moderation stats:", error);
        return NextResponse.json(
            { error: "Internal server error", details: error.message },
            { status: 500 }
        );
    }
}
