const logger = require("../utils/logger");
const { launchBrowser } = require("./browserSession");
const selectors = require("./smileOneSelectors");

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function purchaseTopup({ order, account, dryRun, delayMs }) {
  logger.info("Smile.one automation started", {
    orderId: order.order_id,
    account: account.email,
    dryRun,
  });

  await delay(delayMs);

  if (dryRun) {
    logger.info("Smile.one dry-run purchase completed", {
      orderId: order.order_id,
      game: order.game,
      product: order.product,
      userGameId: order.user_game_id,
    });
    return {
      ok: true,
      dryRun: true,
      reference: `DRY-${order.order_id}`,
    };
  }

  validateSelectors();
  const session = await launchBrowser(account.email);
  try {
    await session.page.goto(session.config.baseUrl, {
      waitUntil: "domcontentloaded",
    });
    await delay(delayMs);

    throw new Error("Smile.one selectors are configured, but the purchase flow still needs site-specific steps");
  } finally {
    await session.browser.close();
  }
}

function validateSelectors() {
  const missing = [];
  for (const [groupName, group] of Object.entries(selectors)) {
    for (const [name, value] of Object.entries(group)) {
      if (!value) missing.push(`${groupName}.${name}`);
    }
  }
  if (missing.length > 0) {
    throw new Error(`Smile.one selectors are not configured: ${missing.join(", ")}`);
  }
}

module.exports = {
  purchaseTopup,
};
