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

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

        // Only Super Admins can execute Archival operations
        if (!currentUser || currentUser.role !== 'super_admin') {
            return NextResponse.json({ error: "Unauthorized. Requires Super Admin role." }, { status: 403 });
        }

        const body = await request.json();
        const { thresholdDays, targetTier } = body;

        const days = thresholdDays || 90;
        const cutoffDate = subDays(new Date(), days);
        const newTier = targetTier || "COLD"; // Usually we move from HOT directly to COLD, or WARM.

        // In a real system, moving to COLD might involve exporting to AWS Glacier / S3
        // and physically deleting from the PostgreSQL live DB.
        // For this implementation, we simulate it by updating the storageTier enum,
        // which tells the UI they are "Archived".

        // 1. Find the target logs
        const targets = await prisma.auditLog.findMany({
            where: {
                created_at: { lt: cutoffDate },
                // Assuming we use (log as any) logic because Prisma client might be stale in this worker
                // We'd technically format this if we want to filter by HOT
            }
        });

        // Filter out those already on target tier (manual check if Prisma types are stale)
        const logsToArchive = targets.filter((l: any) => l.storageTier !== newTier);

        if (logsToArchive.length === 0) {
            return NextResponse.json({ message: "No logs found eligible for archival.", count: 0 });
        }

        const idsToUpdate = logsToArchive.map(l => l.id);

        // 2. Perform the Batch Update
        const updateResult = await prisma.auditLog.updateMany({
            where: { id: { in: idsToUpdate } },
            data: { storageTier: newTier } as any // Cast applied to bypass stale cached prisma type for new field
        });

        // 3. Log the operation natively in the WORM chain
        await LogIntegrityService.appendSecureLog({
            action: "system.logs.archived",
            resource_type: "system",
            user_id: currentUser.id,
            details: {
                recordsArchived: updateResult.count,
                thresholdApplied: `${days} days`,
                targetTier: newTier,
                cutoffDate: cutoffDate.toISOString()
            },
            storageTier: "HOT"
        });

        return NextResponse.json({
            message: `Successfully aggregated and moved ${updateResult.count} logs to ${newTier} storage.`,
            count: updateResult.count
        });

    } catch (error: any) {
        console.error("Archival/Lifecycle Error:", error);
        return NextResponse.json({ error: "Failed to execute archival process" }, { status: 500 });
    }
}
