import { LoggerPort } from 'apps/companion/main/automation/application/ports/LoggerPort';
import { Page } from 'playwright';

export class AuthenticationGuard {
  constructor(
    private readonly page: Page,
    private readonly logger?: LoggerPort
  ) {}

  async checkForLoginUI(): Promise<boolean> {
    const loginSelectors = [
      'text="You are not logged in"',
      ':not(.chakra-menu):not([role="menu"]) button:has-text("Log in")',
      'button[aria-label="Log in"]',
    ];

    for (const selector of loginSelectors) {
      try {
        const element = this.page.locator(selector).first();
        const isVisible = await element.isVisible().catch(() => false);

        if (isVisible) {
          this.logger?.warn('Login UI detected - user not authenticated', {
            selector,
          });
          return true;
        }
      } catch {
        // Selector not found, continue checking
      }
    }

    return false;
  }

  async failFastIfUnauthenticated(): Promise<void> {
    if (await this.checkForLoginUI()) {
      throw new Error('Authentication required: Login UI detected on page');
    }
  }
}