import { expect, test } from '@playwright/test';

const username = process.env.E2E_ADMIN_USERNAME ?? 'admin';
const password = process.env.E2E_ADMIN_PASSWORD;
const baseUrl = (process.env.E2E_BASE_URL ?? 'http://178.104.200.7/taxbaik').replace(/\/$/, '');

test.describe('admin authentication', () => {
  test('logs in through the real browser UI and reaches dashboard', async ({ page }) => {
    test.skip(!password, 'E2E_ADMIN_PASSWORD is required.');

    const consoleErrors: string[] = [];
    const networkRequests: { url: string; status?: number }[] = [];

    page.on('console', message => {
      if (message.type() === 'error') {
        consoleErrors.push(message.text());
      }
    });
    page.on('pageerror', error => {
      consoleErrors.push(error.message);
    });
    page.on('response', response => {
      if (response.url().includes('/api/auth/login') || response.url().includes('/admin/')) {
        networkRequests.push({ url: response.url(), status: response.status() });
      }
    });

    await page.goto(`${baseUrl}/admin/login`);
    await expect(page.locator('input[placeholder="사용자명"]')).toBeVisible();
    await expect(page.locator('input[placeholder="비밀번호"]')).toBeVisible();

    // Wait for form to be fully ready
    await page.waitForTimeout(500);

    const usernameInput = page.locator('input[placeholder="사용자명"]');
    const passwordInput = page.locator('input[placeholder="비밀번호"]');
    const loginButton = page.getByRole('button', { name: '로그인' });

    await usernameInput.fill(username);
    await passwordInput.fill(password);

    // Wait for inputs to register
    await page.waitForTimeout(300);

    // Verify inputs were filled
    const usernameValue = await usernameInput.inputValue();
    const passwordValue = await passwordInput.inputValue();
    console.log(`Username filled: ${usernameValue === username}, Password filled: ${passwordValue === password}`);

    // Click login and wait for any navigation
    await loginButton.click();

    // Wait a bit for form submission + page reload
    await page.waitForTimeout(3000);

    // Check localStorage and current state
    const localStorageData = await page.evaluate(() => ({
      accessToken: localStorage.getItem('accessToken'),
      refreshToken: localStorage.getItem('refreshToken'),
      tokenExpiry: localStorage.getItem('tokenExpiry')
    }));

    console.log(`localStorage has accessToken: ${!!localStorageData.accessToken}`);
    console.log(`Current URL after login: ${page.url()}`);
    console.log(`Network requests: ${JSON.stringify(networkRequests)}`);

    // If we're still on login page, something failed
    if (page.url().includes('/admin/login')) {
      console.log('Still on login page after 3 seconds!');
      // Try to find error message
      const errorMsg = await page.locator('.login-error-message').textContent().catch(() => null);
      console.log(`Error message: ${errorMsg}`);
    }

    await expect(page).toHaveURL(/\/taxbaik\/admin\/dashboard$/, { timeout: 20_000 });
    // WASM 부팅에 시간이 걸릴 수 있으므로 더 긴 타임아웃 사용
    await expect(page.getByRole('heading', { name: '대시보드' }).first()).toBeVisible({ timeout: 60_000 });
    await expect(page.getByRole('link', { name: /로그아웃/ })).toBeVisible({ timeout: 30_000 });
    expect(consoleErrors, 'browser console/page errors').toEqual([]);
  });
});
