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

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

        // Strict RBAC: Compliance reports might contain sensitive overarching data
        if (!currentUser || !['super_admin', 'auditor'].includes(currentUser.role)) {
            return NextResponse.json({ error: "Unauthorized. Requires Super Admin or Auditor role." }, { status: 403 });
        }

        const body = await request.json();
        const { framework, startDate, endDate, adminId, includeHashSignatures } = body;

        if (!framework || !startDate || !endDate) {
            return NextResponse.json({ error: "Missing required report parameters" }, { status: 400 });
        }

        const whereClause: any = {
            created_at: {
                gte: new Date(startDate),
                lte: new Date(endDate)
            }
        };

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

        // Fetch Logs
        const logs = await prisma.auditLog.findMany({
            where: whereClause,
            orderBy: { created_at: "asc" }, // Ascending for chronological compliance tracing
            include: {
                user: { select: { name: true, email: true, role: true } }
            }
        });

        // Frame the Report
        const reportTemplate = {
            metadata: {
                generated_at: new Date().toISOString(),
                generated_by: currentUser.id,
                framework_target: framework,
                period: { start: startDate, end: endDate },
                total_records: logs.length,
                confidentiality: "RESTRICTED",
                cryptographic_verification: includeHashSignatures ? "INCLUDED" : "OMITTED"
            },
            data_access_summary: {},
            system_events: [],
            events: logs.map(log => {
                const baseEvent: any = {
                    event_id: log.id,
                    timestamp: log.created_at,
                    actor_id: log.user_id,
                    actor_details: log.user ? `${log.user.name} (${log.user.email}) - ${log.user.role}` : "SYSTEM/DELETED",
                    action: log.action,
                    resource: `${log.resource_type}:${log.resource_id}`,
                    ip_origin: log.ip_address,
                };

                // GDPR specific field mappings
                if (framework === "GDPR") {
                    baseEvent.data_subject_impact = log.resource_type === 'user' ? "HIGH" : "LOW";
                    baseEvent.consent_or_legitimate_interest = "Platform Administration Terms";
                }

                if (includeHashSignatures) {
                    const l = log as any;
                    baseEvent.signature = l.hash;
                    // Provide a way for the auditor to verify the hash offline
                    baseEvent.is_signature_valid = CryptoService.verifyLogHash(l.hash, {
                        action: l.action,
                        resource_type: l.resource_type,
                        resource_id: l.resource_id,
                        user_id: l.user_id,
                        details: l.details,
                        ip_address: l.ip_address,
                        created_at: l.created_at,
                        previousHash: l.previousHash,
                    });
                }

                return baseEvent;
            })
        };

        // Meta-Audit Log the Report Generation
        await LogIntegrityService.appendSecureLog({
            action: "compliance.report.generated",
            resource_type: "system",
            user_id: currentUser.id,
            details: {
                framework,
                recordsExported: logs.length,
                dateRange: `${startDate} to ${endDate}`
            },
            storageTier: "HOT"
        });

        return NextResponse.json(reportTemplate);

    } catch (error: any) {
        console.error("Compliance Report Error:", error);
        return NextResponse.json({ error: "Failed to generate compliance report" }, { status: 500 });
    }
}
