const pool = require('../db/connection');

const totalrevenue = async (req, res) =>
{
    try{
    const {start_date,end_date} = req.body
    const result = await pool.query('SELECT * FROM totalrevenue_rest($1,$2) as status',[start_date,end_date]);
    const totalrenueve = result.rows[0].status;
    /*const totalrenueve = result.rows.map(re => ({
      total: re.total
    }));*/


    res.json({
        data:totalrenueve
    });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener el dato' });
    }
};

const cogs = async (req, res) =>
{
    try{
    const {start_date,end_date} = req.body;
    const result = await pool.query('SELECT * FROM cogs_rest($1,$2) as status',[start_date,end_date]);
    const cogs = result.rows[0].status;
    /*const cogs = result.rows.map(re => ({
      cogs_total: re.cogs_total,
    }));*/


    res.json({
        message: "Se obtuvieron los ingresos",
        data:cogs
    });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: error });
    }
};

const grossprofit = async (req, res) =>
{
    try{
    const {start_date,end_date} = req.body;
    const result = await pool.query('SELECT * FROM grossprofit_rest($1,$2) as status',[start_date,end_date]);
    const grossprofit = result.rows[0].status;
    /*const grossprofit = result.rows.map(re => ({
      grossprofit: re.grossprofit
    }));*/


    res.json({
        message: "Se obtuvieron los ingresos",
        data:grossprofit
    });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener el dato' });
    }
};


const weightedCategoriesCost = async (req, res) =>
{
    try{
    const {start_date,end_date} = req.body
    const result = await pool.query('SELECT * FROM weighted_categories_rest_cost($1,$2)',[start_date,end_date]);
    const weightedCategoriesCost = result.rows.map(re => ({
      id_expense_cat : re.id_expense_cat ,
      category_name: re.category_name ,
      spanish_name : re.spanish_name ,
      total : re.total,
      participation : re.participation
    }));
    res.json({
        data:weightedCategoriesCost
    });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener el dato' });
    }
};

const ebitda = async (req, res) =>
{
    try{
    const {start_date,end_date} = req.body;
    const result = await pool.query('SELECT * FROM ebitda_rest($1,$2)', [start_date,end_date]);
    const ebitda = result.rows.map(re => ({
      expenses_total: re.expenses_total,
      ebitda : re.ebitda
    }));


    res.json({
        message: "Se obtuvieron los ingresos",
        data:ebitda
    });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener el dato' });
    }
};

module.exports = {ebitda,weightedCategoriesCost,grossprofit,totalrevenue,cogs};
