import crypto from "crypto";

export class CryptoService {
    /**
     * Generates a SHA-256 hash for a log entry to ensure WORM compliance.
     * The hash incorporates the previous log's hash to form a cryptographic chain.
     */
    static generateLogHash(payload: {
        action: string;
        resource_type: string;
        resource_id: string | null;
        user_id: string | null;
        details: any;
        ip_address: string | null;
        created_at: Date;
        previousHash: string | null;
    }): string {
        const dataString = JSON.stringify({
            action: payload.action,
            resource_type: payload.resource_type,
            resource_id: payload.resource_id,
            user_id: payload.user_id,
            details: payload.details,
            ip_address: payload.ip_address,
            created_at: payload.created_at.toISOString(),
            previousHash: payload.previousHash,
            // We can also add a server secret here to prevent offline tampering if the DB is dumped
            secret: process.env.LOG_INTEGRITY_SECRET || "default_dev_secret_xyz123",
        });

        return crypto.createHash("sha256").update(dataString).digest("hex");
    }

    /**
     * Verifies if a provided hash matches the re-computed hash of the payload.
     */
    static verifyLogHash(
        expectedHash: string,
        payload: Parameters<typeof CryptoService.generateLogHash>[0]
    ): boolean {
        const computedHash = this.generateLogHash(payload);
        return computedHash === expectedHash;
    }
}
