const db = require('../database/db');

function createWithdraw({ withdraws_tp, withdraws_amt, withdraws_investment_id, withdraws_fee_id, withdraws_fee_amt, withdraws_date }, callback) {
    const sql = `
      INSERT INTO withdraws (withdraws_tp, withdraws_amt, withdraws_investment_id, withdraws_fee_id, withdraws_fee_amt, withdraws_date)
      VALUES ($1, $2, $3, $4, $5, $6)
      RETURNING withdraws_id
    `;
    const params = [withdraws_tp, withdraws_amt, withdraws_investment_id, withdraws_fee_id, withdraws_fee_amt, withdraws_date];
    db.run(sql, params, function (err, result) { // 'result' contém os dados retornados pelo RETURNING
      if (err) {
        console.error('Erro ao inserir withdraw:', err.message);
        return callback(err);
      }
      // ALTERADO: O ID vem de result.rows[0].withdraws_id em vez de this.lastID
      callback(null, result.rows[0].withdraws_id);
    });
}
 
function getAllWithdraws(callback) {
  const sql = `
    SELECT
      wd.withdraws_id,
      wd.withdraws_investment_id,
      wd.withdraws_fee_id,
      wd.withdraws_tp,
      wd.withdraws_amt,
      wd.withdraws_fee_amt,
      wd.withdraws_date,
      it.investment_type_name AS investment_type,
      f.fee_op AS fee_op,
      f.fee_prorata AS fee_prorata
    FROM withdraws wd
    JOIN investment i        ON wd.withdraws_investment_id = i.investment_id
    JOIN investment_type it  ON i.investment_type_id = it.investment_type_id
    LEFT JOIN fee f          ON wd.withdraws_fee_id = f.fee_id
  `;
  db.all(sql, [], (err, rows) => {
    if (err) {
      console.error('Erro ao listar withdraws:', err.message);
      return callback(err);
    }
    callback(null, rows);
  });
}

function getWithdrawById(withdraws_id, callback) {
    const sql = `
      SELECT
        wd.withdraws_id,
        wd.withdraws_investment_id,
        wd.withdraws_fee_id,
        wd.withdraws_tp,
        wd.withdraws_amt,
        wd.withdraws_fee_amt,
        wd.withdraws_date,
        it.investment_type_name AS investment_type,
        f.fee_op AS fee_op,
        f.fee_prorata AS fee_prorata
      FROM withdraws wd
      JOIN investment i        ON wd.withdraws_investment_id = i.investment_id
      JOIN investment_type it  ON i.investment_type_id = it.investment_type_id
      LEFT JOIN fee f          ON wd.withdraws_fee_id = f.fee_id
      WHERE wd.withdraws_id = $1
    `;
    db.get(sql, [withdraws_id], (err, row) => {
      if (err) {
        console.error('Erro ao buscar withdraw por ID:', err.message);
        return callback(err);
      }
      callback(null, row);
    });
}

function getWithdrawByInvestmentId(withdraws_investment_id, callback) {
    const sql = `
      SELECT
        wd.withdraws_id,
        wd.withdraws_investment_id,
        wd.withdraws_fee_id,
        wd.withdraws_tp,
        wd.withdraws_amt,
        wd.withdraws_fee_amt,
        wd.withdraws_date,
        it.investment_type_name AS investment_type,
        f.fee_op AS fee_op,
        f.fee_prorata AS fee_prorata
      FROM withdraws wd
      JOIN investment i        ON wd.withdraws_investment_id = i.investment_id
      JOIN investment_type it  ON i.investment_type_id = it.investment_type_id
      LEFT JOIN fee f          ON wd.withdraws_fee_id = f.fee_id
      WHERE wd.withdraws_investment_id = $1
    `;
    db.all(sql, [withdraws_investment_id], (err, rows) => { // Mantido db.all pois pode haver várias retiradas para um investimento
      if (err) {
        console.error('Erro ao buscar withdraw por ID de investimento:', err.message);
        return callback(err);
      }
      callback(null, rows);
    });
}

function updateWithdraw(withdraws_id, { withdraws_tp, withdraws_amt, withdraws_investment_id, withdraws_fee_id, withdraws_fee_amt, withdraws_date }, callback) {
  const sql = `
    UPDATE withdraws
    SET withdraws_tp = $1, withdraws_amt = $2, withdraws_investment_id = $3, withdraws_fee_id = $4, withdraws_fee_amt = $5, withdraws_date = $6
    WHERE withdraws_id = $7
  `;
  const params = [withdraws_tp, withdraws_amt, withdraws_investment_id, withdraws_fee_id, withdraws_fee_amt, withdraws_date, withdraws_id];
  db.run(sql, params, function (err, result) { // 'result' é o segundo argumento
    if (err) {
      console.error('Erro ao atualizar withdraw:', err.message);
      return callback(err);
    }
    // ALTERADO: this.changes para result.rowCount
    callback(null, result.rowCount);
  });
}

function deleteWithdraw(withdraws_id, callback) {
  const sql = `DELETE FROM withdraws WHERE withdraws_id = $1`;
  db.run(sql, [withdraws_id], function (err, result) { // 'result' é o segundo argumento
    if (err) {
      console.error('Erro ao remover withdraw:', err.message);
      return callback(err);
    }
    // ALTERADO: this.changes para result.rowCount
    callback(null, result.rowCount);
  });
}

module.exports = {
  // initWithdrawTable, // Removido do export
  createWithdraw,
  getAllWithdraws,
  getWithdrawById,
  getWithdrawByInvestmentId,
  updateWithdraw,
  deleteWithdraw
};