import { Page, BrowserContext } from '@playwright/test';
import { RoleFactory } from '../roles/role-factory';
import { RoleAuthManager } from './role-auth-manager';
import type { RoleDefinition } from '../roles/base.role';

export class AuthHelper {
  constructor(
    private page: Page,
    private context: BrowserContext
  ) {}

  async loginAsRole(roleName: string, useTokenInjection: boolean = true): Promise<void> {
    const role = RoleFactory.getRole(roleName);

    if (useTokenInjection) {
      await this.injectToken(role);
    } else {
      await this.performLogin(role);
    }
  }

  private async injectToken(role: RoleDefinition): Promise<void> {
    const token = await RoleAuthManager.getRoleToken(role.name);
    
    // 注入token到localStorage
    await this.page.addInitScript((token) => {
      localStorage.setItem('token', token);
      localStorage.setItem('username', 'admin');
    }, token);

    // 设置cookie
    await this.context.addCookies([
      {
        name: 'token',
        value: token,
        domain: 'localhost',
        path: '/',
      }
    ]);
  }

  private async performLogin(role: RoleDefinition): Promise<void> {
    await this.page.goto('/login');
    
    await this.page.fill('input[placeholder*="用户名"]', role.credentials.username);
    await this.page.fill('input[placeholder*="密码"]', role.credentials.password);
    await this.page.click('button[type="submit"]');
    
    // 等待登录成功跳转
    await this.page.waitForURL(/\/(dashboard|home)?/, { timeout: 10000 });
  }

  async logout(): Promise<void> {
    await this.page.click('[data-testid="user-menu"]');
    await this.page.click('[data-testid="logout-button"]');
    await this.page.waitForURL('/login');
  }

  async clearAuth(): Promise<void> {
    await this.context.clearCookies();
    await this.page.evaluate(() => {
      localStorage.clear();
      sessionStorage.clear();
    });
  }
}

export async function createAuthenticatedPage(
  page: Page,
  context: BrowserContext,
  roleName: string
): Promise<AuthHelper> {
  const helper = new AuthHelper(page, context);
  await helper.loginAsRole(roleName);
  return helper;
}
