const FormConfig = require("../../models/formConfigModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");

/**
 * GET /api/forms/:key
 * Fetch dynamic form configuration
 */

const getFormByAgent = async (req, res) => {
    try {
        const { key } = req.params;
        console.log(key);
        
        // const { id } = req.params;
        const normalizedKey = key.trim().toUpperCase();
        const userId = req.user?._id;
        const orgId = req.user?.orgId;
        console.log(orgId);


        if (!normalizedKey) {
            return errorResponse(res, "Form key is required", 400);
        }

        const query = {
            key: normalizedKey,
            isActive: true,
        };

        //  Multi-tenant safety
        if (orgId) {
          query.orgId = orgId;
        }

        const form = await FormConfig.findOne(query)
            // const form = await FormConfig.findById(id)
            .select("-__v")
            .lean();

        if (!form) {
            return errorResponse(res, "Form not found or inactive", 404);
        }

        //  Audit log (read action)
        // await logUserAction({
        //     userId,
        //     orgId,
        //     action: "VIEW_FORM_CONFIG",
        //     entity: "FormConfig",
        //     entityId: form._id,
        //     metadata: {
        //         key,
        //     },
        // });

        return res.status(200).json({
            success: true,
            data: form,
        });
    } catch (error) {
        console.error("GET FORM ERROR:", error);
        return errorResponse(res, "Failed to fetch form configuration", 500, error);
    }
};


module.exports = {
    getFormByAgent,
}