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

const TARGET_INDEX_NAME = "transaction_1";

const run = async () => {
  const collection = models.request.collection;
  const indexes = await collection.indexes();
  const existingIndex = indexes.find((index) => index.name === TARGET_INDEX_NAME);

  if (existingIndex) {
    await collection.dropIndex(TARGET_INDEX_NAME);
  }

  await collection.createIndex(
    { transaction: 1 },
    {
      name: TARGET_INDEX_NAME,
      unique: true,
      partialFilterExpression: {
        transaction: { $type: "objectId" },
      },
    },
  );

  console.log(
    JSON.stringify(
      {
        droppedExistingIndex: Boolean(existingIndex),
        recreatedIndex: TARGET_INDEX_NAME,
      },
      null,
      2,
    ),
  );
};

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