/**
 * Smoke: partial then full refund on one paid booking (restores nothing — use carefully).
 * Skips if no eligible booking. Usage:
 *   npx tsx --env-file=.env scripts/smoke-refund.ts
 */
import { connectDb, disconnectDb } from "../src/db/mongoose";
import { Booking, LedgerEntry, Refund } from "../src/db/models";
import { recordRefund, getReconciliationSummary } from "../src/services/ledger";
import { toNumber } from "../src/lib/serialize";

async function main() {
  await connectDb();
  const booking = await Booking.findOne({
    deletedAt: null,
    "payment.status": "PAID",
    $or: [{ refundLyd: { $exists: false } }, { refundLyd: 0 }],
  });
  if (!booking) {
    console.log("No eligible PAID booking for smoke refund — skipping");
    await disconnectDb();
    return;
  }

  const total = toNumber(booking.totalLyd);
  const partial = Math.round(Math.min(1, total * 0.05) * 100) / 100;
  console.log("booking", String(booking._id), "totalLyd", total, "partial", partial);

  const r1 = await recordRefund({
    booking,
    type: "PARTIAL",
    amountLyd: partial > 0 ? partial : 0.01,
    reasonCode: "ADMIN_ADJUSTMENT",
    reasonNote: "smoke partial",
    source: "ADMIN",
  });
  console.log("partial:", {
    status: r1.bookingStatus,
    payment: r1.paymentStatus,
    refundLyd: r1.refundLyd,
  });

  // reload
  const again = await Booking.findById(booking._id);
  if (!again) throw new Error("booking missing");
  const r2 = await recordRefund({
    booking: again,
    type: "FULL",
    amountLyd: 1,
    reasonCode: "ADMIN_ADJUSTMENT",
    reasonNote: "smoke full",
    source: "ADMIN",
  });
  console.log("full:", {
    status: r2.bookingStatus,
    payment: r2.paymentStatus,
    refundLyd: r2.refundLyd,
  });

  const ledgers = await LedgerEntry.countDocuments({
    bookingId: String(booking._id),
    type: "REFUND",
  });
  const refunds = await Refund.countDocuments({ bookingId: String(booking._id) });
  const summary = await getReconciliationSummary();
  console.log({ ledgers, refunds, refundsLyd: summary.refundsLyd, net: summary.netBalanceLyd });

  await disconnectDb();
}

main().catch(async (err) => {
  console.error(err);
  try {
    await disconnectDb();
  } catch {
    /* ignore */
  }
  process.exit(1);
});
