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

export async function GET(request: Request) {
    try {
        const currentUser = await getCurrentUser();

        // 1. RBAC: Determine Access Level
        const allowedRoles = ['super_admin', 'admin', 'moderator', 'auditor'];
        if (!currentUser || !allowedRoles.includes(currentUser.role)) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
        }

        const role = currentUser.role;
        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 actionFilter = searchParams.get("action");
        let adminFilter = searchParams.get("admin_id");
        const startDate = searchParams.get("startDate");
        const endDate = searchParams.get("endDate");
        const search = searchParams.get("search");

        const whereClause: any = {};

        // RBAC: Moderators can only see THEIR OWN logs
        if (role === 'moderator') {
            adminFilter = currentUser.id;
        }

        if (actionFilter && actionFilter !== 'all') {
            whereClause.action = { startsWith: actionFilter };
        }

        if (adminFilter && adminFilter !== 'all') {
            whereClause.user_id = adminFilter;
        }

        if (startDate || endDate) {
            whereClause.created_at = {};
            if (startDate) whereClause.created_at.gte = new Date(startDate);
            if (endDate) whereClause.created_at.lte = new Date(endDate);
        }

        // Search in text description or resource_id
        if (search) {
            whereClause.OR = [
                { action: { contains: search, mode: 'insensitive' } },
                { resource_id: { contains: search, mode: 'insensitive' } },
                { resource_type: { contains: search, mode: 'insensitive' } }
            ];
        }

        const [logs, total] = await Promise.all([
            prisma.auditLog.findMany({
                where: whereClause,
                skip,
                take: limit,
                orderBy: { created_at: "desc" },
                include: {
                    user: {
                        select: {
                            id: true,
                            name: true,
                            email: true,
                            role: true,
                            avatar_url: true
                        }
                    }
                }
            }),
            prisma.auditLog.count({ where: whereClause })
        ]);

        // Calculate Quick Stats for last 24h
        const oneDayAgo = subHours(new Date(), 24);
        const last24hLogs = await prisma.auditLog.findMany({
            where: {
                created_at: { gte: oneDayAgo },
                ...(adminFilter && adminFilter !== 'all' ? { user_id: adminFilter } : {})
            },
            select: {
                user_id: true,
                action: true,
                details: true
            }
        });

        const uniqueAdmins = new Set(last24hLogs.map(l => l.user_id).filter(Boolean)).size;
        const totalActions = last24hLogs.length;

        // Count suspicious/failed events
        const suspiciousEvents = last24hLogs.filter(l => {
            const isFailedAction = l.action.toLowerCase().includes('fail');
            let isSevere = false;
            if (l.details && typeof l.details === 'object') {
                const det = l.details as any;
                if (det.severity === 'ERROR' || det.severity === 'CRITICAL' || det.severity === 'ban') {
                    isSevere = true;
                }
            }
            return isFailedAction || isSevere;
        }).length;

        // 2. Data Redaction (Protect PII based on role)
        const isSuperAdmin = role === 'super_admin';
        const redactedLogs = logs.map(log => {
            const redactedLog = { ...log };
            if (!isSuperAdmin) {
                // Redact IP
                if (redactedLog.ip_address) {
                    redactedLog.ip_address = "***.***.***.***";
                }
                // Deep redact details (masking emails if they exist in standard places)
                if (redactedLog.details && typeof redactedLog.details === 'object') {
                    const det = { ...(redactedLog.details as any) };
                    if (det.email) det.email = det.email.replace(/(.{2}).*(@.*)/, "$1***$2");
                    if (det.passwordResetToken) det.passwordResetToken = "[REDACTED]";
                    redactedLog.details = det;
                }
            }
            return redactedLog;
        });

        // 3. Meta-Audit Log (Record that logs were accessed)
        // Background non-awaitable Promise to avoid slowing down the dashboard load
        Promise.resolve().then(async () => {
            try {
                await LogIntegrityService.appendSecureLog({
                    action: "security.logs.read",
                    resource_type: "system",
                    user_id: currentUser.id,
                    details: {
                        searchQuery: search,
                        page,
                        roles: currentUser.role,
                        recordsReturned: redactedLogs.length
                    },
                });
            } catch (err) {
                console.error("Failed to append secure meta-audit log", err);
            }
        });

        return NextResponse.json({
            data: redactedLogs,
            meta: {
                total,
                page,
                limit,
                totalPages: Math.ceil(total / limit)
            },
            stats: {
                last24h: {
                    totalActions,
                    uniqueAdmins,
                    suspiciousEvents
                }
            }
        });

    } catch (error: any) {
        console.error("Audit Logs Fetch Error:", error);
        return NextResponse.json({ error: error.message || "Failed to fetch audit logs" }, { status: 500 });
    }
}
