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

const baseUrl = process.env.E2E_BASE_URL || 'http://localhost:5001/taxbaik';
const username = process.env.E2E_ADMIN_USERNAME || 'test_admin';
const password = process.env.E2E_ADMIN_PASSWORD || 'TestAdmin@123456';

test.describe('Admin Pages E2E (Manual)', () => {
  let token: string;

  test.beforeAll(async () => {
    // Login and get token
    const response = await fetch(`${baseUrl}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    });

    if (!response.ok) {
      throw new Error(`Login failed: ${response.status}`);
    }

    const data = await response.json();
    token = data.accessToken;
    console.log(`✅ Logged in. Token: ${token?.substring(0, 20)}...`);
  });

  test('Login page loads', async ({ page }) => {
    await page.goto(`${baseUrl}/admin/login`);
    await expect(page.locator('text=관리자 로그인')).toBeVisible();
    await expect(page.locator('input[placeholder*="사용자"]')).toBeVisible();
  });

  test('Dashboard page loads', async ({ page }) => {
    await page.goto(`${baseUrl}/admin/dashboard`);
    await page.context().addCookies([{
      name: 'Authorization',
      value: `Bearer ${token}`,
      url: baseUrl
    }]);
    await page.reload();

    // Check if dashboard loaded
    const content = await page.content();
    expect(content.includes('대시보드') || content.includes('세무')).toBeTruthy();

    // Screenshot
    await page.screenshot({ path: 'test-results/dashboard.png' });
    console.log('✅ Dashboard screenshot saved');
  });

  test('Blog page loads', async ({ page }) => {
    await page.goto(`${baseUrl}/admin/blog`);
    await page.context().addCookies([{
      name: 'Authorization',
      value: `Bearer ${token}`,
      url: baseUrl
    }]);
    await page.reload();

    const content = await page.content();
    const loaded = content.includes('블로그') || page.url().includes('/admin/blog');
    console.log(`Blog page loaded: ${loaded}, URL: ${page.url()}`);

    await page.screenshot({ path: 'test-results/blog.png' });
    console.log('✅ Blog screenshot saved');
  });

  test('Inquiry page loads', async ({ page }) => {
    await page.goto(`${baseUrl}/admin/inquiries`);
    await page.context().addCookies([{
      name: 'Authorization',
      value: `Bearer ${token}`,
      url: baseUrl
    }]);
    await page.reload();

    const content = await page.content();
    const loaded = content.includes('문의') || page.url().includes('/admin/inquiries');
    console.log(`Inquiry page loaded: ${loaded}, URL: ${page.url()}`);

    await page.screenshot({ path: 'test-results/inquiries.png' });
    console.log('✅ Inquiries screenshot saved');
  });

  test('CRM pages load', async ({ page }) => {
    const pages = [
      '/admin/tax-profiles',
      '/admin/contracts',
      '/admin/consulting-activities'
    ];

    for (const adminPage of pages) {
      await page.goto(`${baseUrl}${adminPage}`);
      await page.context().addCookies([{
        name: 'Authorization',
        value: `Bearer ${token}`,
        url: baseUrl
      }]);
      await page.reload();

      const url = page.url();
      console.log(`✅ Page loaded: ${adminPage} (URL: ${url})`);

      await page.screenshot({ path: `test-results/${adminPage.split('/').pop()}.png` });
    }
  });
});
