const requestFormModel = require("../models/requestForm");

const createForm = async (req, res) => {
    const newForm = new requestFormModel(req.body);
    const location = {
        type: "Point",
        coordinates: [ parseFloat(req.body.longitude), parseFloat(req.body.latitude) ],
        locationName: req.body.locationName || null
    };
    newForm.location = location;
    const result = await newForm.save();
    return result;
};

const getFormById = async (req, res) => {
    const { formId } = req.query;

    const form = await requestFormModel.findById(formId);
    return form;
};

const getAllForms = async (req) => {
    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 requestFormModel.find(filter).populate({
            path: "userId",
            select: "-password"
        });
        return forms
    } else {
        const forms = await requestFormModel.find(filter).populate({
            path: "technicianId",
            select: "-password"
        });
        return forms
    }

};

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

    if(req.body.longitude && req.body.latitude){
        updatedData.location = {
            type: "Point",
            coordinates: [ parseFloat(req.body.longitude), parseFloat(req.body.latitude) ],
            locationName: req.body.locationName || null
        }
    };

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

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

module.exports = {
    createForm,
    getFormById,
    getAllForms,
    updateFormById,
    deleteForm
}