import { mongoConnection } from "$connections/index.js";
import models from "$models/index.js";

const run = async () => {
  const requests = await models.request
    .find({ transaction: { $exists: true, $ne: null } })
    .select("_id transaction paymentMethod operationType trackId")
    .lean();

  let linkedCount = 0;
  let alreadyLinkedCount = 0;
  let missingTransactionCount = 0;
  let clearedPlaceholderCount = 0;

  for (const request of requests) {
    const transactionId = request.transaction;
    if (!transactionId) {
      continue;
    }

    const transaction = await models.transaction
      .findById(transactionId)
      .select("_id request");

    if (!transaction) {
      missingTransactionCount += 1;

      if (
        request.paymentMethod === "slip" ||
        request.operationType === "redemption"
      ) {
        await models.request.updateOne(
          { _id: request._id, transaction: transactionId },
          { $unset: { transaction: 1 } },
        );
        clearedPlaceholderCount += 1;
      }

      continue;
    }

    if (String(transaction.request || "") === String(request._id)) {
      alreadyLinkedCount += 1;
      continue;
    }

    transaction.request = request._id;
    await transaction.save();
    linkedCount += 1;
  }

  console.log(
    JSON.stringify(
      {
        scannedRequests: requests.length,
        linkedCount,
        alreadyLinkedCount,
        missingTransactionCount,
        clearedPlaceholderCount,
      },
      null,
      2,
    ),
  );
};

try {
  await run();
} catch (error) {
  console.error("Backfill failed:", error);
  process.exitCode = 1;
} finally {
  await mongoConnection.close();
}
