import { Page } from '@playwright/test';

/**
 * 认证辅助工具
 * 帮助测试进行用户认证和状态管理
 */

export interface UserSession {
  token: string;
  userId: number;
  expiresAt: number;
}

/**
 * 设置用户登录状态
 */
export async function setAuthenticated(page: Page, userId: number = 10001): Promise<void> {
  await page.addInitScript((uid: number) => {
    // 设置localStorage模拟登录
    localStorage.setItem('token', `test-token-${Date.now()}`);
    localStorage.setItem('userId', uid.toString());
    localStorage.setItem('authTime', Date.now().toString());
  }, userId);
}

/**
 * 设置API Key
 */
export async function setApiKey(page: Page, apiKey: string): Promise<void> {
  await page.addInitScript((key: string) => {
    localStorage.setItem('apiKey', key);
  }, apiKey);
}

/**
 * 设置活动上下文
 */
export async function setActivityContext(page: Page, activityId: number): Promise<void> {
  await page.addInitScript((aid: number) => {
    localStorage.setItem('activityId', aid.toString());
    localStorage.setItem('currentActivity', JSON.stringify({ id: aid }));
  }, activityId);
}

/**
 * 清除所有认证状态
 */
export async function clearAuthentication(page: Page): Promise<void> {
  await page.evaluate(() => {
    localStorage.removeItem('token');
    localStorage.removeItem('userId');
    localStorage.removeItem('apiKey');
    localStorage.removeItem('activityId');
    localStorage.removeItem('authTime');
    localStorage.removeItem('currentActivity');
  });
}

/**
 * 检查是否已登录
 */
export async function isAuthenticated(page: Page): Promise<boolean> {
  return await page.evaluate(() => {
    const token = localStorage.getItem('token');
    return !!token;
  });
}

/**
 * 等待登录状态
 */
export async function waitForAuthentication(page: Page, timeout: number = 5000): Promise<void> {
  const startTime = Date.now();
  
  while (Date.now() - startTime < timeout) {
    if (await isAuthenticated(page)) {
      return;
    }
    await page.waitForTimeout(100);
  }
  
  throw new Error('等待登录状态超时');
}

/**
 * 模拟OAuth登录流程
 */
export async function simulateOAuthLogin(
  page: Page, 
  provider: string = 'wechat'
): Promise<void> {
  // 点击登录按钮
  const loginButton = page.locator('[data-testid="login-button"], .login-btn, text=登录').first();
  
  if (await loginButton.isVisible().catch(() => false)) {
    await loginButton.click();
  }
  
  // 等待登录弹窗或跳转
  await page.waitForTimeout(1000);
  
  // 设置模拟的登录状态
  await setAuthenticated(page);
  
  console.log(`   模拟${provider}登录完成`);
}

/**
 * 获取当前用户信息
 */
export async function getCurrentUser(page: Page): Promise<{ userId: number | null; token: string | null }> {
  return await page.evaluate(() => {
    return {
      userId: localStorage.getItem('userId') ? parseInt(localStorage.getItem('userId')!) : null,
      token: localStorage.getItem('token'),
    };
  });
}
