/**
 * Product URL Normalizer
 *
 * Repairs malformed source URLs created by older scrapers, so follow-up image
 * and detail fetchers can reach the actual product pages.
 */
import { pool } from "./db";
import { logger } from "./logger";

async function normalizeProductUrls(): Promise<void> {
  logger.info("=== Product URL Normalizer ===");

  const mouserDe = await pool.query(`
    UPDATE transceivers
    SET product_page_url = regexp_replace(
          product_page_url,
          '^https://www\\.mouser\\.dehttps://www\\.mouser\\.de',
          'https://www.mouser.de'
        ),
        updated_at = NOW()
    WHERE product_page_url LIKE 'https://www.mouser.dehttps://www.mouser.de%'
    RETURNING id
  `);

  const mouserCom = await pool.query(`
    UPDATE transceivers
    SET product_page_url = regexp_replace(
          product_page_url,
          '^https://www\\.mouser\\.comhttps://www\\.mouser\\.com',
          'https://www.mouser.com'
        ),
        updated_at = NOW()
    WHERE product_page_url LIKE 'https://www.mouser.comhttps://www.mouser.com%'
    RETURNING id
  `);

  logger.info("Product URL normalizer complete", {
    mouser_de_fixed: mouserDe.rowCount ?? 0,
    mouser_com_fixed: mouserCom.rowCount ?? 0,
  });
}

if (require.main === module) {
  normalizeProductUrls()
    .then(() => pool.end())
    .catch((err) => {
      logger.error("Product URL normalizer failed", { error: (err as Error).message });
      pool.end();
      process.exit(1);
    });
}
