import prisma from "@/lib/prisma";
import { CryptoService } from "./CryptoService";

export class LogIntegrityService {
    /**
     * Securely appends a new audit log to the database.
     * Fetches the very last log's hash to form a chain.
     * Using a transaction guarantees atomicity if multiple logs are inserted concurrently.
     */
    static async appendSecureLog(data: {
        action: string;
        resource_type: string;
        resource_id?: string | null;
        user_id?: string | null;
        details?: Record<string, unknown> | null;
        ip_address?: string | null;
        user_agent?: string | null;
        storageTier?: "HOT" | "WARM" | "COLD";
    }) {
        // We use an interactive transaction to prevent race conditions when finding the `previousHash`
        return await prisma.$transaction(async (tx) => {
            // 1. Find the most recent log
            const lastLog = await tx.auditLog.findFirst({
                orderBy: { created_at: "desc" },
                select: { hash: true },
            });

            const previousHash = lastLog?.hash || null;
            const createdAt = new Date(); // Lock the timestamp for the hash

            // 2. Compute the new hash based on the payload + timestamp + previousHash
            const hash = CryptoService.generateLogHash({
                action: data.action,
                resource_type: data.resource_type,
                resource_id: data.resource_id ?? null,
                user_id: data.user_id ?? null,
                details: data.details ?? null,
                ip_address: data.ip_address ?? null,
                created_at: createdAt,
                previousHash,
            });

            // 3. Insert the fully-signed log
            return await tx.auditLog.create({
                data: {
                    ...data,
                    created_at: createdAt,
                    hash,
                    previousHash,
                } as any,
            });
        });
    }

    /**
     * Scans the database chain of logs and validates the cryptographic sequence.
     * Throws an error or returns false if tampering or corruption is detected.
     */
    static async verifyChain(): Promise<{
        intact: boolean;
        brokenAtId?: string;
        message: string;
        totalVerified: number;
    }> {
        // For large logs, this should use chunking/pagination in a real system.
        // We fetch in chronological order so Log[N].previousHash === Log[N-1].hash
        const logs = await prisma.auditLog.findMany({
            orderBy: { created_at: "asc" },
            select: {
                id: true,
                action: true,
                resource_type: true,
                resource_id: true,
                user_id: true,
                details: true,
                ip_address: true,
                created_at: true,
                hash: true,
                previousHash: true,
            },
        });

        if (logs.length === 0) {
            return { intact: true, message: "No logs strictly verified.", totalVerified: 0 };
        }

        let expectedPreviousHash: string | null = null;
        let verifiedCount = 0;

        for (const log of logs) {
            // 1. Check the chain link (Does this log point to the correct previous hash?)
            // The very first log in history will have expectedPreviousHash = null
            if (log.previousHash !== expectedPreviousHash) {
                return {
                    intact: false,
                    brokenAtId: log.id,
                    message: `Chain broken at Log ID ${log.id}. The previousHash doesn't match the preceding log.`,
                    totalVerified: verifiedCount,
                };
            }

            // 2. Verify the contents of the log haven't been tampered with
            const isContentValid = CryptoService.verifyLogHash(log.hash, {
                action: log.action,
                resource_type: log.resource_type,
                resource_id: log.resource_id,
                user_id: log.user_id,
                details: log.details,
                ip_address: log.ip_address,
                created_at: log.created_at,
                previousHash: log.previousHash,
            });

            if (!isContentValid) {
                return {
                    intact: false,
                    brokenAtId: log.id,
                    message: `Content mutation detected at Log ID ${log.id}. Found hash: ${log.hash}`,
                    totalVerified: verifiedCount,
                };
            }

            // Prepare for next iteration
            expectedPreviousHash = log.hash;
            verifiedCount++;
        }

        return {
            intact: true,
            message: "All logs verified intact.",
            totalVerified: verifiedCount,
        };
    }
}
