const readline = require('readline');
const config = require('../src/config');
const logger = require('../src/logger');
const { launchBrowser } = require('../src/session');

function waitForEnter() {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => {
    rl.question('Залогинься в браузере, потом нажми Enter здесь...\n', () => {
      rl.close();
      resolve();
    });
  });
}

(async () => {
  const browser = await launchBrowser({ headless: config.authHeadless });
  const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
  const page = await context.newPage();

  logger.info(`Opening base URL: ${config.baseUrl}`);
  await page.goto(config.baseUrl, { waitUntil: 'domcontentloaded' });

  await waitForEnter();

  await context.storageState({ path: config.sessionFile });
  logger.info(`Session saved to ${config.sessionFile}`);

  await browser.close();
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
