const slugify = require("slugify");
const SellersCompany = require("../../models/SellersCompany");

exports.setSellerUrlHandle = async (req, res, next) => {
  try {
    const sellerCompanies = await SellersCompany.findAll();
    const seenHandles = new Map();

    for (const sellerCompany of sellerCompanies) {
      const { id, shop_name, company_name, url_handle } = sellerCompany;

      const baseHandle = slugify(shop_name?.trim() || company_name?.trim() || "", {
        lower: true,
        remove: /[*+~.()'"!:@]/g,
      });

      let uniqueHandle = baseHandle;
      let counter = 2;

      while (seenHandles.has(uniqueHandle)) {
        uniqueHandle = `${baseHandle}-${counter}`;
        counter++;
      }

      seenHandles.set(uniqueHandle, true);

      if (url_handle === uniqueHandle) {
        continue;
      }

      await SellersCompany.update({ url_handle: uniqueHandle }, { where: { id } });

      console.log(`Updated seller ID ${id}: ${uniqueHandle}`);
    }

    res.status(200).json({ message: "URL handles updated successfully." });
  } catch (err) {
    next(err);
  }
};
