// Fast pass: just prefixes every image key missing a folder with the right
// folder name, as a single bulkWrite per collection — no S3 calls, so it's
// not subject to the per-item latency (and Atlas TLS flakiness) that the
// combined migrate-add-folder-prefix.ts script hits when it also verifies/
// repairs each object in S3. Run migrate-add-folder-prefix.ts afterward (or
// instead) if you also want missing S3 objects backfilled with a placeholder.
import "../config/env";
import mongoose from "mongoose";
import { databaseConnect, databaseDisconnect } from "../database/functions";

const PRODUCTS_FOLDER = process.env.AWS_S3_PRODUCTS_FOLDER;
const STORES_FOLDER = process.env.AWS_S3_STORES_FOLDER;

const hasFolder = (key: string) => key.includes("/");

async function migrate() {
  if (!PRODUCTS_FOLDER || !STORES_FOLDER) {
    console.error(
      "AWS_S3_PRODUCTS_FOLDER / AWS_S3_STORES_FOLDER not set in .env",
    );
    process.exit(1);
  }

  await databaseConnect();
  console.log("Connected to MongoDB");

  // ---- products.images ----
  const products = mongoose.connection.collection("products");
  const productDocs = await products
    .find({ images: { $exists: true, $ne: [] } })
    .toArray();
  console.log(`Products scanned: ${productDocs.length}`);

  const productOps = [];
  for (const p of productDocs) {
    const images: unknown[] = Array.isArray(p.images) ? p.images : [];
    if (!images.some((img) => typeof img === "string" && !hasFolder(img))) {
      continue;
    }
    const newImages = images.map((img) =>
      typeof img === "string" && !hasFolder(img)
        ? `${PRODUCTS_FOLDER}/${img}`
        : img,
    );
    productOps.push({
      updateOne: {
        filter: { _id: p._id },
        update: { $set: { images: newImages } },
      },
    });
  }

  if (productOps.length > 0) {
    const result = await products.bulkWrite(productOps);
    console.log(`Products updated: ${result.modifiedCount}`);
  } else {
    console.log("No products missing a folder prefix.");
  }

  // ---- storeInformations.storeImage ----
  const stores = mongoose.connection.collection("storeinformations");
  const storeDocs = await stores
    .find({ storeImage: { $exists: true, $ne: "" } })
    .toArray();
  console.log(`Store info docs scanned: ${storeDocs.length}`);

  const storeOps = [];
  for (const s of storeDocs) {
    if (typeof s.storeImage !== "string" || hasFolder(s.storeImage)) continue;
    storeOps.push({
      updateOne: {
        filter: { _id: s._id },
        update: { $set: { storeImage: `${STORES_FOLDER}/${s.storeImage}` } },
      },
    });
  }

  if (storeOps.length > 0) {
    const result = await stores.bulkWrite(storeOps);
    console.log(`Store info docs updated: ${result.modifiedCount}`);
  } else {
    console.log("No store info docs missing a folder prefix.");
  }

  await databaseDisconnect();
}

migrate().catch((err) => {
  console.error("Migration failed:", err);
  process.exit(1);
});
