const { StatusCodes } = require("http-status-codes")
const { mustContainProperties } = require("../utils")
const Company = require("../models/Company")
const getIntegrationsConfig = require("../utils/getIntegrationsConfig")

const integration = async (req, res) => {
    const { companyId } = req.params
    const { config, name } = req.body

    mustContainProperties(req, ['name', 'config'])

    const company = await Company.findOne({ companyId })

    if (!company) {
        return res.status(StatusCodes.NOT_FOUND).send({ msg: "companyId not found!" })
    }

    const existingIntegrationIndex = company.integrations.findIndex(i => i.name === name)

    if (existingIntegrationIndex !== -1) {
        company.integrations[existingIntegrationIndex].config = config
    } else {
        company.integrations.push({ name, config })
    }

    await company.save()  

    res.status(StatusCodes.OK).send({
        msg: 'Integração atualizada com sucesso',
        integrations: company.integrations
    })
}

module.exports = {
    integration
}



