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

export async function GET(request: Request) {
    try {
        // 1. Authorization: Only super_admins can run a full chain integrity scan
        // Note: Adjust the import and getCurrentUser call based on your actual auth setup
        /* 
        const user = await getCurrentUser();
        if (!user || user.role !== "super_admin") {
          return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }
        */

        // 2. Perform the cryptographic scan
        const scanResult = await LogIntegrityService.verifyChain();

        // 3. Log the scan itself (Meta-Audit)
        // We do NOT use the secure append here to avoid an infinite loop if the chain is broken,
        // but in a production environment, you might log failures securely.
        await prisma.auditLog.create({
            data: {
                action: "security.logs.integrity_scan",
                resource_type: "system",
                details: {
                    result: scanResult.intact ? "SUCCESS" : "FAILURE",
                    message: scanResult.message,
                    totalVerified: scanResult.totalVerified,
                    brokenAtId: scanResult.brokenAtId,
                    category: "SECURITY",
                    severity: scanResult.intact ? "INFO" : "CRITICAL",
                },
            }
        });

        // 4. Return results
        if (!scanResult.intact) {
            return NextResponse.json(scanResult, { status: 409 }); // Conflict / Integrity failure
        }

        return NextResponse.json(scanResult);

    } catch (error) {
        console.error("Integrity Scan Error:", error);
        return NextResponse.json(
            { error: "Internal Server Error during integrity scan" },
            { status: 500 }
        );
    }
}
