/**
 * Copyright (C) 2025 Brainformatik GmbH (info@brainformatik.com)
 *
 * This file is part of brainX.
 * All Rights Reserved.
 *
 * This part of brainX can not be copied and/or distributed without the
 * express permission of Brainformatik GmbH.
 */

export class LoginPage {
  constructor(page) {
    this.page = page;
  }

  async goto(query = '', {
    demo = true,
    autoLogin = false 
  } = {}) {
    const suffix = query || '';
    const demoParam = demo ? (suffix ? '&demo=1' : '?demo=1') : '';
    const autoLoginParam = autoLogin && process.env.PLAYWRIGHT_TEST === '1'
      ? `${suffix || demoParam ? '&' : '?'}autologin=1`
      : '';
    await this.page.goto(`/login${suffix}${demoParam}${autoLoginParam}`);
    await this.page.waitForLoadState('networkidle');
    const loginContent = this.page.locator('.login-content');
    await Promise.race([
      loginContent.waitFor({
        state: 'visible'
      }),
      this.page.waitForURL((url) => !url.pathname.startsWith('/login'), {
        timeout: 60000
      })
    ]);
  }

  async signIn({
    username, password 
  }) {
    const currentPath = new URL(this.page.url()).pathname;
    if (!currentPath.startsWith('/login')) {
      return;
    }
    const usernameById = this.page.locator('#login-username');
    const passwordById = this.page.locator('#login-password');
    const demoToggle = this.page.getByLabel(/Enable demo data/i);

    if (await demoToggle.count()) {
      if (!(await demoToggle.isChecked())) {
        await demoToggle.check();
      }
    }

    if (await usernameById.count()) {
      await usernameById.waitFor({
        state: 'visible' 
      });
      await usernameById.fill(username);
    } else {
      const usernameField = this.page.getByLabel(/Username/i);
      await usernameField.waitFor({
        state: 'visible' 
      });
      await usernameField.fill(username);
    }

    if (await passwordById.count()) {
      await passwordById.fill(password);
    } else {
      const passwordField = this.page.getByLabel(/Password/i);
      await passwordField.fill(password);
    }

    await Promise.all([
      this.page.waitForLoadState('networkidle'),
      this.page.getByTestId('btn-login-submit').click()
    ]);
  }
}
