const pool = require('../db/connection');
const axios = require('axios');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const getFacturas = async (initialDate, finalDate) => {
  try {
    const response = await axios.get(process.env.FACTURAS_API_URL, {
      params: {
        issuerRfc: process.env.FACTURAS_ISSUER_RFC,
        type: process.env.FACTURAS_TYPE,
        initialDate: initialDate,
        finalDate: finalDate
      },
      headers: {
        Authorization: `Bearer ${process.env.FACTURAS_API_TOKEN}`
      },
      timeout: 15000
    });

    return response.data;

  } catch (error) {
    console.error(
      'Error API Facturas:',
      error.response?.data || error.message
    );
    throw error;
  }
  
};
const addfacturas = async (req, res) => {
try {
  const now = new Date();

  const startOfYear = new Date(now.getFullYear(), 0, 1, 0, 0, 0);
  //console.log(startOfYear);
  const formatDateTime = (date) =>
      date.toISOString().slice(0, 19).replace('T', ' ');
  const FACTURAS_INITIAL_DATE = formatDateTime(startOfYear);
  const FACTURAS_FINAL_DATE   = formatDateTime(now);
    console.log(FACTURAS_INITIAL_DATE);
    console.log(FACTURAS_FINAL_DATE);
  const facturas = await getFacturas(FACTURAS_INITIAL_DATE,FACTURAS_FINAL_DATE);
  
   const result = await pool.query('SELECT addhoruxdata($1::jsonb) as total',[JSON.stringify(facturas)]);
  const total = result.rows[0].total;
    res.json({
      message: 'Facturas subidas a la base de datos',
      total
    });

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



const getCategoryIncome = async (req, res) => {
    try{
         const result = await pool.query('SELECT * FROM getcategoryincome()');

    const categoriesIncome = result.rows.map(inc => ({
      id_cat_income: inc.id_cat_income,
      name_cat_income: inc.name_cat_income,
      english_name: inc.english_name
    }));
    res.json({
        data:categoriesIncome
    });

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

};

const getInvoiceIncome = async (req, res) => {
    try{
         const result = await pool.query('SELECT * FROM getinvoiceincome()');

    const invoiceIncome = result.rows.map(inc => ({
      id_inv_income: inc.id_inv_income,
      name_inv_income: inc.name_inv_income,
      amount: inc.amount,
      dateinvoice: inc.dateinvoice

    }));
    res.json({
        data:invoiceIncome
    });

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

};

const getAccountIncome = async (req, res) => {
    try{
         const result = await pool.query('SELECT * FROM getaccountincome()');

    const aacountIncome = result.rows.map(inc => ({
      id_acc_income: inc.id_acc_income,
      name_acc_income: inc.name_acc_income,
    }));
    res.json({
        data:aacountIncome
    });

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

};

const getIncomeHorux = async (req, res) => {
    try{
    const result = await pool.query('SELECT * FROM getincomehorux()');

    const incomeHorux = result.rows.map(inc => ({
      id_hrx_income: inc.id_hrx_income,
      date_in: inc.date_in,
      createddate: inc.createddate,
      account_name: inc.account_name,
      categories: inc.categories,
      amount:inc.amount,
      amountinvoice: inc.amountinvoice,
      invoice: inc.invoice,
      status_in: inc.status_in
    }));
    res.json({
        data:incomeHorux
    });

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

};
const getTotalIncome = async (req, res) => {
    try{
    const result = await pool.query('SELECT * FROM gettotalincome() as total');

    const totalIncome = result.rows[0].total;

    res.json({
      message: 'Total de income',
      data: totalIncome
    });

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

};

const newIncome = async (req, res) => {
    try{
    const {
        account_id,
        amount,
        new_date,
        newinvoice,
        area_id,
        categories,

    } = req.body;
    const categoriesJson = categories ? JSON.stringify(categories) : '[]';

    const result = await pool.query('SELECT newincome($1,$2,$3,$4,$5,$6::jsonb) AS status',[
    account_id,amount,new_date,newinvoice,area_id,categoriesJson]);
   const newIncome = result.rows[0].status;
   res.json({
              message: "Income agregado correctamente",
              new_expense: newIncome
            });
          }
    catch(error)
    {
    console.error(error);
    res.status(500).json(error);
    }

};

const getOneIncome = async (req, res) => {
    try{
    const { id } = req.params;
    const result = await pool.query('SELECT * FROM getoneincome($1)',[parseInt(id)]);

    const incomeHorux = result.rows.map(inc => ({
      id_hrx_income: inc.id_hrx_income,
      date_in: inc.date_in,
      account_id: inc.account_id,
      amount:inc.amount,
      invoice: inc.invoice,
      categories: inc.categories
    }));
    res.json({
        data:incomeHorux
    });

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

};

const updateIncome = async (req, res) => {
    try{
    const {id} = req.params;
    const {
        account_id,
        amount,
        up_date,
        up_invoice,
        area_id,
        categories
    } = req.body;
        const categoriesJson = categories ? JSON.stringify(categories) : '[]';

    const result = await pool.query('SELECT updateincome($1,$2,$3,$4,$5,$6,$7::jsonb) AS status',[
    id,account_id,amount,up_date,up_invoice,area_id,categoriesJson]);
   const newIncome = result.rows[0].status;
   res.json({
              message: "Income actualizado correctamente",
              new_expense: newIncome
            });
          }
    catch(error)
    {
    console.error(error);
    res.status(500).json(error);
    }

};
const getstripeservice = async (req, res) => {
  try{
     /*const paymentIntent = await stripe.paymentIntents.create({
      amount: 4805510,
      currency: 'usd',
      payment_method: 'pm_card_visa',
      confirm: true,
      automatic_payment_methods: {
        enabled: true,
        allow_redirects: 'never'
      }
    });*/
    const balanceTransactions = await stripe.transfers.list();
    const result = await pool.query(
          'SELECT addstripedatav2($1::jsonb) AS inserted',
          [JSON.stringify(balanceTransactions)]);
    res.json({
              message: "Se obtuvieron datos de stripe y se insertaron",
              transactions: result.rows[0].inserted,
              //data: balanceTransactions
            });
  }
      catch(error)
    {
    console.error(error);
    res.status(500).json(error);
    }


};
const addDemostripeData  = async (req, res) => {
  try{
    const transfer = await stripe.transfers.create({
    amount: 1000, // centavos
     currency: 'usd',
     destination: 'acct_1Sm54nEzzXSLq34b',
    transfer_group: 'ORDER_95',});
    res.json({
      message: 'Pago creado y confirmado',
      transfer 
    });
  }catch(error)
    {
    console.error(error);
    res.status(500).json(error);
    }


};


module.exports = {getCategoryIncome,getInvoiceIncome,getAccountIncome,
  getIncomeHorux,getTotalIncome,newIncome,getOneIncome,updateIncome,getFacturas,addfacturas,getstripeservice,
  addDemostripeData};