const discussionFormModel = require("../models/discussionForm");

const createDiscussionForm = async (req) => {
    const newDiscussion = new discussionFormModel(req.body);
    const result = await newDiscussion.save();
    return result
};

const getDiscussionFormById = async (req) => {
    const { discussionFormId } = req.query;
    const form = await discussionFormModel.findById(discussionFormId);
    return form
};

const getAllDiscussionForms = async (req) => {

    console.log("first :", req.query);
    const { userId, technicianId, status } = req.query;
    const filter = {};
    if(userId){
        filter.userId = userId
    };
    if(technicianId){
        filter.technicianId = technicianId
    };
    if(status){
        filter.status = status
    };

    if(filter.technicianId){
        const forms = await discussionFormModel.find(filter).populate({
            path: "userId",
            select: "fullName profileImage locationName longitude latitude"
        });;
        return forms;
    } else {
        const forms = await discussionFormModel.find(filter).populate({
            path: "technicianId",
            select: "-password"
        }).populate("serviceId");
        return forms;
    }
};

const updateDiscussionForm = async (req) => {
    const { formId } = req.body;
    const updatedData = req.body;

    const form = await discussionFormModel.findByIdAndUpdate(formId, 
        { $set: updatedData },
        { new: true }
    );
    return form 
};

const deleteDiscussionForm = async (req) => {
    const { formId } = req.query;
    const form = await discussionFormModel.findByIdAndDelete(formId);
    return form
};

module.exports = {
    createDiscussionForm,
    getDiscussionFormById,
    getAllDiscussionForms,
    updateDiscussionForm,
    deleteDiscussionForm
};