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[] = [];
    page.on('console', message => {
      if (message.type() === 'error') {
        consoleErrors.push(message.text());
      }
    });
    page.on('pageerror', error => {
      consoleErrors.push(error.message);
    });

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

    await page.locator('input[placeholder="사용자명"]').fill(username);
    await page.locator('input[placeholder="비밀번호"]').fill(password);
    await page.getByRole('button', { name: '로그인' }).click();

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