const fs = require('fs');
const { chromium } = require('playwright');
const logger = require('./logger');

async function launchBrowser({ headless }) {
  return chromium.launch({
    headless,
    args: [
      '--disable-blink-features=AutomationControlled',
      '--no-sandbox',
      '--disable-dev-shm-usage'
    ]
  });
}

async function createContext({ browser, sessionFile }) {
  const hasState = fs.existsSync(sessionFile);
  logger.info(`Using session file: ${sessionFile} (${hasState ? 'found' : 'missing'})`);

  return browser.newContext(
    hasState
      ? {
          storageState: sessionFile,
          viewport: { width: 1440, height: 900 }
        }
      : {
          viewport: { width: 1440, height: 900 }
        }
  );
}

function hasSessionFile(sessionFile) {
  return fs.existsSync(sessionFile);
}

async function saveSessionState(context, sessionFile) {
  await context.storageState({ path: sessionFile });
  logger.info(`Session saved to ${sessionFile}`);
}

async function performBackgroundLogin(page, config) {
  if (!config.authEnabled) {
    throw new Error('Authentication is required, but AUTH_ENABLED=false');
  }

  if (!config.authUsername || !config.authPassword) {
    throw new Error('Authentication is enabled, but AUTH_USERNAME or AUTH_PASSWORD is empty');
  }

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

  const usernameInput = page.locator(config.authUsernameSelector).first();
  const passwordInput = page.locator(config.authPasswordSelector).first();

  await usernameInput.waitFor({ state: 'visible', timeout: config.requestTimeoutMs });
  await passwordInput.waitFor({ state: 'visible', timeout: config.requestTimeoutMs });

  await usernameInput.fill(config.authUsername);
  await passwordInput.fill(config.authPassword);

  const submit = page.locator(config.authSubmitSelector).first();
  await submit.waitFor({ state: 'visible', timeout: config.requestTimeoutMs });

  await Promise.all([
    page.waitForLoadState('networkidle').catch(() => null),
    submit.click()
  ]);

  if (config.authSuccessSelector) {
    await page.locator(config.authSuccessSelector).first().waitFor({
      state: 'visible',
      timeout: config.requestTimeoutMs
    });
  }

  logger.info('Background authentication completed');
}

async function authenticateContext({ context, sessionFile, config }) {
  const page = await context.newPage();

  try {
    await performBackgroundLogin(page, config);
    await saveSessionState(context, sessionFile);
  } finally {
    await page.close().catch(() => undefined);
  }
}

module.exports = {
  launchBrowser,
  createContext,
  hasSessionFile,
  authenticateContext,
  performBackgroundLogin
};
