const { logger } = require("nodejs-log-agent");
const { cors_origin } = require("../models");

const getData = async (req, res) => {
    try {
        const corsOrigins = await cors_origin.findAll();
        return res.status(200).json({
            status :true,
            message : "success",
            data : corsOrigins
        });
    } catch (error) {
        logger.error("[Function-Cors] GET : ", { message : error.message , stack : error.stack, error : error });
        res.status(500).json({
            status: false,
            message: error.message,
            error
        });
    }
}

const create = async (req, res) => {
    const { origin, is_active = true } = req.body;
    try {
        const corsOrigin = await cors_origin.create({ origin, is_active });
        return res.status(201).json({
            status :true,
            message : "Added data Successfully",
            data : corsOrigin
        });
    } catch (error) {
        logger.error("[Function-Cors] POST : ", { message : error.message , stack : error.stack, error : error });
        res.status(500).json({
            status: false,
            message: error.message,
            error
        });
    }
}

const update = async (req, res) => {
    const { id } = req.params;
    const { origin, is_active } = req.body;
    try {
        const [rowsUpdated] = await cors_origin.update({ origin, is_active }, { where: { id } });

        if (rowsUpdated === 0) {
            return res.status(404).json({ status: false, message: "Data not found" });
        }

        const updatedData = await cors_origin.findByPk(id);
        return res.status(200).json({
            status :true,
            message : "Updated data Successfully",
            data : updatedData
        });
    } catch (error) {
        logger.error("[Function-Cors] PUT : ", { message : error.message , stack : error.stack, error : error });
        res.status(500).json({
            status: false,
            message: error.message,
            error
        });
    }
}

const remove = async (req, res) => {
    const { id } = req.params;
    try {
        const rowsDeleted = await cors_origin.destroy({ where: { id } });

        if (rowsDeleted === 0) {
            return res.status(404).json({ status: false, message: "Data not found" });
        }

        return res.status(200).json({
            status :true,
            message : "Removed data Successfully"
        });
    } catch (error) {
        logger.error("[Function-Cors] DELETE : ", { message : error.message , stack : error.stack, error : error });
        res.status(500).json({
            status: false,
            message: error.message,
            error
        });
    }
}

module.exports = { getData, create, update, remove }