// One-time migration: strips the full S3 domain off existing image values,
// leaving just the relative key (e.g. "btd-products/169...-file.jpg"). The
// domain is reconstructed on read via utils/imageUrl.ts, so rows only need
// to store the key going forward. Safe to re-run — rows already stored as
// a bare key are left untouched.
//
// Legacy rows are virtual-hosted-style S3 URLs where the bucket name IS the
// category folder, e.g. https://btd-products.s3.amazonaws.com/169...jpg ->
// "btd-products/169...jpg". No S3 lookups here — this only rewrites the
// stored string.
import "../config/env";
import mongoose from "mongoose";
import { databaseConnect, databaseDisconnect } from "../database/functions";

const isFullUrl = (value: unknown): value is string =>
  typeof value === "string" && /^https?:\/\//i.test(value);

function toKey(url: string): string {
  const parsed = new URL(url);
  const folder = parsed.hostname.split(".")[0]; // "btd-products" from "btd-products.s3.amazonaws.com"
  const filename = decodeURIComponent(parsed.pathname.replace(/^\/+/, ""));
  return `${folder}/${filename}`;
}

async function migrate() {
  // Reuses functions.ts's SRV-DNS workaround and retry logic instead of
  // connecting directly — connecting straight via mongoose.connect() skips
  // that fix and fails with querySrv ECONNREFUSED on networks whose local
  // DNS resolver refuses SRV lookups.
  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(isFullUrl)) continue;

    const newImages = images.map((img) => (isFullUrl(img) ? toKey(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 with full-URL images found.");
  }

  // ---- 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 (!isFullUrl(s.storeImage)) continue;
    storeOps.push({
      updateOne: {
        filter: { _id: s._id },
        update: { $set: { storeImage: toKey(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 with a full-URL storeImage found.");
  }

  await databaseDisconnect();
}

migrate().catch((err) => {
  console.error("Migration failed:", err);
  process.exit(1);
});
