const { isString } = require("lodash");
const { sendServerEmail } = require("../email/sendemail");
const logger = require("../utils/logger");
const { raw } = require("express");

const SUPPORT_EMAIL = "patrick@imexsystems.ca";

const safeJsonParse = (maybeJson) => {
    if (!isString(maybeJson)) return null;
    try {
        return JSON.parse(maybeJson);
    } catch {
        return null;
    }
};


const handleBillAiFeedback = async (req, res) => {
    try {
        const rating = req.body?.rating;
        const comments = isString(req.body?.comments) ? req.body?.comments?.trim() : "";

        const billFormValues = safeJsonParse(req.body?.billFormValues);
        const rawAIData = safeJsonParse(req.body?.rawAIData);

        const jobid = billFormValues?.jobid || billFormValues?.jobId || "unknown";
        const shopname = req.body?.shopname || "unknown";
        const subject = `Bill AI Feedback (${rating === "up" ? "+" : "-"}) Shop=${shopname} jobid=${jobid}`;

        const text = [
            `User: ${req?.user?.email || "unknown"}`,
            `Rating: ${rating}`,
            comments ? `Comments: ${comments}` : "Comments: (none)",
            "",
            "Form Values (User):",
            JSON.stringify(billFormValues, null, 4),
            "",
            "Raw AI Data:",
            JSON.stringify(rawAIData, null, 4)
        ]
            .filter(Boolean)
            .join("\n");

        const attachments = [];
        if (req.file?.buffer) {
            attachments.push({
                filename: req.file.originalname || `bill-${jobid}.pdf`,
                content: req.file.buffer,
                contentType: req.file.mimetype || "application/pdf"
            });
        }

        await sendServerEmail({
            to: [SUPPORT_EMAIL],
            subject,
            type: "text",
            text,
            attachments
        });

        return res.json({ success: true });
    } catch (error) {
        logger.log("bill-ai-feedback-error", "ERROR", req?.user?.email, null, {
            message: error?.message,
            stack: error?.stack
        });
        return res.status(500).json({ message: "Failed to submit feedback" });
    }
};

module.exports = {
    handleBillAiFeedback
};
