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

/**
 * Helper: Busca o `investment_type_id` dado um `investment_type_name`.
 * Retorna `null` se não encontrar.
 */
function getItIdByName(investment_type_name, callback) {
  // ALTERADO: ? para $1
  const sql = `SELECT investment_type_id FROM investment_type WHERE investment_type_name = $1`;
  db.get(sql, [investment_type_name], (err, row) => {
    if (err) return callback(err);
    if (!row) return callback(null, null);
    return callback(null, row.investment_type_id);
  });
}

/**
 * Helper: Busca o `btc_value_id` dado uma data (YYYY-MM-DD).
 * Retorna `null` se não encontrar.
 */
function getBtcvIdByDate(dateStr, callback) {
 
  const sql = `SELECT btc_value_id FROM btc_value WHERE btc_value_date = $1`;
  db.get(sql, [dateStr], (err, row) => {
    if (err) return callback(err);
    if (!row) return callback(null, null);
    return callback(null, row.btc_value_id);
  });
}

/**
 * SELECT * (com JOIN) para listar todos os registros de investment_rentability,
 * retornando também o nome do tipo de investimento e as datas de início/fim.
 */
function getAllRentabilities(callback) {
  const sql = `
    SELECT
      ir.investment_rentability_id,
      ir.investment_rentability_api_rent,
      it.investment_type_name AS investment_type_name,
      bs.btc_value_date AS btcv_start_date,
      be.btc_value_date AS btcv_end_date
    FROM investment_rentability ir
    JOIN investment_type it ON ir.investment_rentability_investment_type_id = it.investment_type_id
    JOIN btc_value bs       ON ir.investment_rentability_btcv_start = bs.btc_value_id
    JOIN btc_value be       ON ir.investment_rentability_btcv_end   = be.btc_value_id
  `;
  db.all(sql, [], (err, rows) => {
    if (err) {
      console.error('Erro ao buscar rentabilities:', err.message);
      return callback(err);
    }
    callback(null, rows);
  });
}

/**
 * SELECT por ID (com JOIN) para retornar um registro específico.
 */
function getRentabilityById(investment_rentability_id, callback) {

  const sql = `
    SELECT
      ir.investment_rentability_id,
      ir.investment_rentability_api_rent,
      it.investment_type_name AS investment_type_name,
      bs.btc_value_date AS btcv_start_date,
      be.btc_value_date AS btcv_end_date
    FROM investment_rentability ir
    JOIN investment_type it ON ir.investment_rentability_investment_type_id = it.investment_type_id
    JOIN btc_value bs       ON ir.investment_rentability_btcv_start = bs.btc_value_id
    JOIN btc_value be       ON ir.investment_rentability_btcv_end   = be.btc_value_id
    WHERE ir.investment_rentability_id = $1
  `;
  db.get(sql, [investment_rentability_id], (err, row) => {
    if (err) {
      console.error('Erro ao buscar rentability by ID:', err.message);
      return callback(err);
    }
    callback(null, row);
  });
}

/**
 * Cria um novo registro na tabela investment_rentability,
 * baseado em investment_type_name (-> investment_type_id), btcv_start_date (-> btc_value_id), btcv_end_date (-> btc_value_id).
 */
function createRentability({ investment_type_name, btcv_start_date, btcv_end_date, investment_rentability_api_rent }, callback) {
  // 1) Buscar investment_type_id via investment_type_name
  getItIdByName(investment_type_name, (err, investment_type_id) => {
    if (err) return callback(err);
    if (!investment_type_id) {
      // Tipo de investimento não encontrado
      return callback(new Error('Tipo de investimento não encontrado.'));
    }
    // 2) Buscar btc_value_id para start date
    getBtcvIdByDate(btcv_start_date, (err2, btcv_start_id) => {
      if (err2) return callback(err2);
      if (!btcv_start_id) {
        return callback(new Error(`btcv_start_date não encontrado: ${btcv_start_date}`));
      }
      // 3) Buscar btc_value_id para end date
      getBtcvIdByDate(btcv_end_date, (err3, btcv_end_id) => {
        if (err3) return callback(err3);
        if (!btcv_end_id) {
          return callback(new Error(`btcv_end_date não encontrado: ${btcv_end_date}`));
        }
        // 4) Fazer INSERT
        const sql = `
          INSERT INTO investment_rentability (investment_rentability_investment_type_id, investment_rentability_btcv_start, investment_rentability_btcv_end, investment_rentability_api_rent)
          VALUES ($1, $2, $3, $4)
          RETURNING investment_rentability_id
        `;
        const params = [investment_type_id, btcv_start_id, btcv_end_id, investment_rentability_api_rent];

        db.run(sql, params, function (err4, result) { // 'result' contém os dados retornados pelo RETURNING
          if (err4) {
            console.error('Erro ao inserir em investment_rentability:', err4.message);
            return callback(err4);
          }
          // ALTERADO: O ID vem de result.rows[0].investment_rentability_id em vez de this.lastID
          callback(null, result.rows[0].investment_rentability_id);
        });
      });
    });
  });
}

/**
 * Atualiza um registro existente em investment_rentability.
 * Mesmo processo de lookup de investment_type_id, btc_value_id, etc.
 */
function updateRentability(investment_rentability_id, { investment_type_name, btcv_start_date, btcv_end_date, investment_rentability_api_rent }, callback) {
  getItIdByName(investment_type_name, (err, investment_type_id) => {
    if (err) return callback(err);
    if (!investment_type_id) {
      return callback(new Error('Tipo de investimento não encontrado.'));
    }

    getBtcvIdByDate(btcv_start_date, (err2, btcv_start_id) => {
      if (err2) return callback(err2);
      if (!btcv_start_id) {
        return callback(new Error(`btcv_start_date não encontrado: ${btcv_start_date}`));
      }

      getBtcvIdByDate(btcv_end_date, (err3, btcv_end_id) => {
        if (err3) return callback(err3);
        if (!btcv_end_id) {
          return callback(new Error(`btcv_end_date não encontrado: ${btcv_end_date}`));
        }

        const sql = `
          UPDATE investment_rentability
          SET investment_rentability_investment_type_id = $1, investment_rentability_btcv_start = $2, investment_rentability_btcv_end = $3, investment_rentability_api_rent = $4
          WHERE investment_rentability_id = $5
        `;
        const params = [investment_type_id, btcv_start_id, btcv_end_id, investment_rentability_api_rent, investment_rentability_id];

        db.run(sql, params, function (err4, result) { // 'result' é o segundo argumento
          if (err4) {
            console.error('Erro ao atualizar investment_rentability:', err4.message);
            return callback(err4);
          }
          // ALTERADO: this.changes para result.rowCount
          callback(null, result.rowCount);
        });
      });
    });
  });
}

/**
 * Remove um registro de investment_rentability (DELETE).
 */
function deleteRentability(investment_rentability_id, callback) {
  // ALTERADO: ? para $1
  const sql = `
    DELETE FROM investment_rentability
    WHERE investment_rentability_id = $1
  `;
  db.run(sql, [investment_rentability_id], function (err, result) { // 'result' é o segundo argumento
    if (err) {
      console.error('Erro ao remover investment_rentability:', err.message);
      return callback(err);
    }
    // ALTERADO: this.changes para result.rowCount
    callback(null, result.rowCount);
  });
}

module.exports = {
  // initInvestmentRentabilityTable, // Removido
  getAllRentabilities,
  getRentabilityById,
  createRentability,
  updateRentability,
  deleteRentability
};