const validator = require("validator");
const logger = require("../../../../handlers/logger");
const {
  formatCurrencyForObjects,
} = require("../../../../managers/customFormaters");
const db = require("../../../../managers/dbConfig");
const {
  transformDateTimeField,
} = require("../../../../managers/formatDateTime");

// ✅ Get Patient Wallet Transaction History
const getPatientWalletTxns = async (req, res) => {
  const { page, limit, offset, q, start_date, end_date, search_type } =
    req.pagination;
  // console.log(q);
  // console.log(start_date);
  // console.log(end_date);
  // console.log(search_type);

  let where = `WHERE 1`;
  let params = [];

  if (q) {
    where += ` AND (patient_id LIKE ? OR tx_ref LIKE ?)`;
    params.push(`%${q}%`, `%${q}%`);
  }

  if (search_type && ["credit", "debit"].includes(search_type.toLowerCase())) {
    where += ` AND transaction_type = ?`;
    params.push(search_type.toLowerCase());
  }

  if (start_date && end_date) {
    where += ` AND DATE(t.date_time) BETWEEN ? AND ?`;
    params.push(start_date, end_date);
  }

  const sql = `SELECT * FROM patient_wallet_txn ${where} ORDER BY date_time DESC LIMIT ? OFFSET ?`;
  const countSql = `SELECT COUNT(*) as total FROM patient_wallet_txn ${where}`;
  params.push(limit, offset);

  const connection = await db.getConnection();
  try {
    const [rows] = await connection.execute(sql, params);
    const [countRow] = await connection.execute(countSql, params.slice(0, -2));
    connection.release();
    let formattedRows = transformDateTimeField(rows);
    res.status(200).json({
      status: "success",
      page,
      total: countRow[0].total,
      data: formattedRows,
    });
  } catch (error) {
    connection.release();
    res.status(500).json({ status: "failed", error });
  }
};

// ✅ Get Family/Group Wallet Transaction History
const getFamilyWalletTxns = async (req, res) => {
  const { page, limit, offset, q, start_date, end_date, search_type } =
    req.pagination;
  // console.log(q);
  // console.log(start_date);
  // console.log(end_date);
  // console.log(search_type);

  let where = `WHERE 1`;
  let params = [];

  if (q) {
    where += ` AND (f.name LIKE ? OR t.tx_ref LIKE ?)`;
    params.push(`%${q}%`, `%${q}%`);
  }

  if (search_type && ["credit", "debit"].includes(search_type.toLowerCase())) {
    where += ` AND t.transaction_type = ?`;
    params.push(search_type.toLowerCase());
  }

  if (start_date && end_date) {
    where += ` AND DATE(t.date_time) BETWEEN ? AND ?`;
    params.push(start_date, end_date);
  }

  const sql = `
    SELECT t.*, f.name as family_name
    FROM family_wallet_tx t
    JOIN families f ON f.id = t.family_id
    ${where}
    ORDER BY t.date_time DESC
    LIMIT ? OFFSET ?`;

  const countSql = `
    SELECT COUNT(*) as total
    FROM family_wallet_tx t
    JOIN families f ON f.id = t.family_id
    ${where}`;

  params.push(limit, offset);

  const connection = await db.getConnection();
  try {
    const [rows] = await connection.execute(sql, params);
    const [countRow] = await connection.execute(countSql, params.slice(0, -2));
    connection.release();
    let formattedRows = transformDateTimeField(rows);
    res.status(200).json({
      status: "success",
      page,
      total: countRow[0].total,
      data: formattedRows,
    });
  } catch (error) {
    connection.release();
    res.status(500).json({ status: "failed", error });
  }
};

module.exports = { getFamilyWalletTxns, getPatientWalletTxns };
