import { Request, Response, NextFunction } from "express";
import * as crypto from 'node:crypto';
import { config } from "dotenv";
config();

const SECRET_KEY = process.env.ENCRYPTION_SECRET_KEY as string;
const ALGORITHM = process.env.ENCRYPTION_ALGORITHM as string;
const IV_LENGTH = parseInt(process.env.IV_LENGTH as string, 10);


function decrypt(encryptedBase64: string): string {
    try {

        const parts = encryptedBase64.split(':');
        const iv = Buffer.from(parts[0], 'base64');
        const encryptedText = Buffer.from(parts[1], 'base64');

        const decipher = crypto.createDecipheriv(ALGORITHM, Buffer.from(SECRET_KEY, 'utf8'), iv);
        const decrypted = Buffer.concat([decipher.update(encryptedText), decipher.final()]);
        return decrypted.toString('utf8');


    }
    catch (error: any) {
        throw new Error(error);
    }
}

export function decryptBodyMiddleware(req: Request, res: Response, next: NextFunction) {
    try {
        if (req.headers['app'] == SECRET_KEY) {
            return next();
        }
        if (req.body && typeof req.body.payload === 'string') {
            const encryptedBase64 = req.body.payload;
            const decryptedText = decrypt(encryptedBase64);
            req.body = JSON.parse(decryptedText);
        }
        next();
    } catch (err: any) {
        console.error('Decryption error:', err.message);
        res.status(400).json({ error: 'Invalid or unprocessable encrypted payload', status: false });
    }
}