import fs from "fs";
import path from "path";
import { createLog } from "../../logger/logger.js";

const cleanStringForFilename = (str: string) => {
    // Remove CRLF and LF newlines
    return str.replace(/(\r\n|\n|\r)/gm, " "); // or "" if you want no space at all
};

/**
 * Save XML string to /xml/ with timestamp in name
 * @param xmlContent The XML string
 * @param prefix File prefix (ex: request or response)
 */
export const saveXml = (xmlContent: string, nameString: string = "request") => {
    const prefix = cleanStringForFilename(nameString);
    try {
        const now = new Date();

        // Format YYYYMMDDHHmm
        const timestamp = `${now.getFullYear()}-${String(
            now.getMonth() + 1
        ).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}-${String(
            now.getHours()
        ).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}`;

        // Ensure xml folder path is always relative to project root
        const xmlDir = path.resolve(process.cwd(), "xml");
        const filePath = path.join(xmlDir, `${prefix}_${timestamp}.xml`);

        // Make sure xml folder exists
        if (!fs.existsSync(xmlDir)) {
            fs.mkdirSync(xmlDir, { recursive: true });
        }

        // Save file
        fs.writeFileSync(filePath, xmlContent, "utf-8");

        createLog(
            "info",
            "notification",
            "notification",
            `XML saved to: ${filePath}`
        );
    } catch (error) {
        createLog(
            "error",
            "notification",
            "notification",
            `Error saving XML:", ${JSON.stringify(error)}`
        );
    }
};
