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

const username = process.env.E2E_ADMIN_USERNAME ?? 'test_admin';
const password = process.env.E2E_ADMIN_PASSWORD ?? 'TestAdmin@123456';
const baseUrl = (process.env.E2E_BASE_URL ?? 'https://www.taxbaik.com').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('#Username')).toBeVisible();
    await expect(page.locator('#Password')).toBeVisible();

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

    const usernameInput = page.locator('#Username');
    const passwordInput = page.locator('#Password');
    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 Promise.all([
      page.waitForURL(/\/admin\/dashboard$/, { timeout: 30_000 }).catch(() => {}),
      loginButton.click()
    ]);

    await page.waitForLoadState('networkidle').catch(() => {});

    // 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)}`);

    await expect(page).toHaveURL(/\/admin\/dashboard$/, { timeout: 20_000 });
    await expect(page.locator('.admin-page-hero')).toBeVisible({ timeout: 60_000 });
    await expect(page.locator('.admin-page-hero')).toContainText('대시보드');
    await expect(page.getByRole('link', { name: /로그아웃/ })).toBeVisible({ timeout: 30_000 });
    expect(consoleErrors, 'browser console/page errors').toEqual([]);
  });
});
