import readline from "readline/promises";
import { stdin, stdout } from "process";
import db from "../models/index.js";
import PsbService from "../thirdParties/psbService.js";

/**
 * READ-ONLY interactive script.
 *
 * Prompts for a Transaction table's primary key (id column — NOT the transaction_id
 * reference string), looks that single transaction up, and requeries it against 9PSB to
 * report its true status.
 *
 * This script only ever READS from the database (Transaction.findByPk) and makes an outbound
 * status-check call to 9PSB. It never calls .update(), .create(), .increment(), or
 * .decrement() on anything — no database writes are possible.
 *
 * Usage: node src/scripts/requeryById.js
 */

const { Transaction } = db;

async function run() {
  const rl = readline.createInterface({ input: stdin, output: stdout });
  const id = (await rl.question("Enter the Transaction table ID (primary key, not the reference string): ")).trim();
  rl.close();

  if (!id) {
    console.error("❌ No ID provided. Exiting — nothing was read or changed.");
    return;
  }

  const tx = await Transaction.findByPk(id);

  if (!tx) {
    console.error(`❌ No Transaction found with id "${id}".`);
    return;
  }

  console.log("\n📄 Transaction found:");
  console.log(`   id: ${tx.id}`);
  console.log(`   transaction_id (reference sent to 9PSB): ${tx.transaction_id}`);
  console.log(`   class: ${tx.class} | type: ${tx.type}`);
  console.log(`   amount: NGN ${parseFloat(tx.amount).toLocaleString()}`);
  console.log(`   local status: ${tx.status}`);
  console.log(`   createdAt: ${tx.createdAt.toISOString()}`);

  if (tx.class !== "payout") {
    console.log(`\n⚠️  Note: this requery mechanism (9PSB's wallet_requery) is built for payouts. This transaction's class is "${tx.class}", so the result may not be meaningful.`);
  }

  console.log("\n🔍 Requerying against 9PSB...\n");

  try {
    const result = await PsbService.walletRequery({
      transactionId: tx.transaction_id,
      amount: Math.round(parseFloat(tx.amount)),
      transactionType: "OTHER_BANKS",
      transactionDate: tx.createdAt.toISOString().split("T")[0],
      accountNo: "",
    }, "AIRPERO");

    console.log("✅ 9PSB response:");
    console.log(JSON.stringify(result, null, 2));

    console.log(`\nSummary: 9PSB reports status = "${result?.status || "unknown"}" (local DB still shows "${tx.status}" — this script did not change it).`);
  } catch (err) {
    console.error("❌ Requery call failed:", err.response?.data || err.message);
  }
}

run()
  .catch((err) => {
    console.error("❌ Script error:", err);
    process.exitCode = 1;
  })
  .finally(() => {
    db.sequelize.close();
  });
