import fs from "fs";
import path from "path";

const LOG_DIR = path.resolve("logs");
const LOG_FILE = path.join(LOG_DIR, "unrecorded-payouts.jsonl");

/**
 * Durable, database-independent record of a payout that 9PSB was told to process (or
 * explicitly confirmed) but whose local database write failed to persist — e.g. the database
 * itself was unreachable at that exact moment. Appended to a local file so the record survives
 * even when the database is the thing that's down.
 *
 * A separate standalone worker (src/scripts/recoverUnrecordedPayoutsWorker.js) reads this file
 * periodically and reconciles each entry back into the database once it's reachable again.
 *
 * Uses a synchronous append, which the OS treats as atomic for writes under a few KB — safe
 * for concurrent writers (e.g. multiple PM2 cluster workers) without needing a file lock.
 */
export function logUnrecordedPayout(entry) {
  try {
    if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
    const line = JSON.stringify({ ...entry, loggedAt: new Date().toISOString() }) + "\n";
    fs.appendFileSync(LOG_FILE, line);
    console.error(
      `🚨 CRITICAL: payout ${entry.transactionReference} could not be recorded in the database — logged to ${LOG_FILE} for automatic recovery.`
    );
  } catch (fileError) {
    // Last resort: if we can't even write to the file, there's nothing more we can do
    // automatically. Make this as loud as possible in the process logs.
    console.error(
      "🚨🚨🚨 CATASTROPHIC: failed to write payout recovery log — manual intervention required.",
      fileError,
      JSON.stringify(entry)
    );
  }
}

export function getRecoveryLogPath() {
  return LOG_FILE;
}
