import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { subHours } from "date-fns";

export type SecurityAnomaly = {
    id: string;
    ruleName: string;
    severity: "MEDIUM" | "HIGH" | "CRITICAL";
    description: string;
    detectedAt: string;
    relatedAdminId?: string;
    evidenceCount: number;
};

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

        const anomalies: SecurityAnomaly[] = [];
        const now = new Date();
        const past24Hours = subHours(now, 24);

        // Fetch logs for the last 24 hours to analyze
        const recentLogs = await prisma.auditLog.findMany({
            where: { created_at: { gte: past24Hours } },
            select: { id: true, action: true, user_id: true, created_at: true, details: true }
        });

        // --- Rule 1: High Failure Rate (Brute force or compromised credential guess)
        // More than 5 failed logins or failed actions from a single user ID in 24h
        const failCounts: Record<string, number> = {};
        recentLogs.forEach(log => {
            if (log.action.toLowerCase().includes('fail')) {
                const uid = log.user_id || 'anonymous';
                failCounts[uid] = (failCounts[uid] || 0) + 1;
            }
        });

        Object.entries(failCounts).forEach(([uid, count]) => {
            if (count >= 5) {
                anomalies.push({
                    id: `anomaly-fail-${uid}`,
                    ruleName: "High Authentication Failure Rate",
                    severity: "CRITICAL",
                    description: `Multiple failed actions or authentication attempts detected for this entity.`,
                    detectedAt: now.toISOString(),
                    relatedAdminId: uid === 'anonymous' ? undefined : uid,
                    evidenceCount: count,
                });
            }
        });

        // --- Rule 2: Suspicious Admin Behavior (Modifying roles or system settings)
        // e.g. An admin changing another user's role to super_admin
        const superAdminPromotions = recentLogs.filter(log =>
            log.action === 'user.role.updated' &&
            log.details && typeof log.details === 'object' &&
            (log.details as any).newRole === 'super_admin'
        );

        if (superAdminPromotions.length > 0) {
            anomalies.push({
                id: `anomaly-superadmin-promo`,
                ruleName: "Privilege Escalation Detected",
                severity: "HIGH",
                description: `A user account was promoted to super_admin privileges in the last 24 hours. Verify this was authorized.`,
                detectedAt: superAdminPromotions[superAdminPromotions.length - 1].created_at.toISOString(),
                evidenceCount: superAdminPromotions.length,
            });
        }

        // --- Rule 3: Mass Job Deletion or Mass Rejection
        const massDeletions: Record<string, number> = {};
        recentLogs.forEach(log => {
            if (['job.deleted', 'job.rejected'].includes(log.action)) {
                if (log.user_id) massDeletions[log.user_id] = (massDeletions[log.user_id] || 0) + 1;
            }
        });

        Object.entries(massDeletions).forEach(([uid, count]) => {
            if (count >= 20) {
                anomalies.push({
                    id: `anomaly-massdel-${uid}`,
                    ruleName: "Mass Content Deletion/Rejection",
                    severity: "MEDIUM",
                    description: `An admin deleted or rejected an unusually high volume of jobs (${count}) recently.`,
                    detectedAt: now.toISOString(),
                    relatedAdminId: uid,
                    evidenceCount: count,
                });
            }
        });

        return NextResponse.json({ anomalies });

    } catch (error: any) {
        console.error("Anomaly Detection Error:", error);
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}
