import { expect, test } from '@playwright/test';
import { loginThroughAdminUi } from './helpers/admin-auth';

const username = process.env.E2E_ADMIN_USERNAME ?? 'admin';
const password = process.env.E2E_ADMIN_PASSWORD || 'Admin@123456';
const baseUrl = (process.env.E2E_BASE_URL ?? 'https://www.taxbaik.com').replace(/\/$/, '');

test.describe('blog CRUD operations', () => {
  test('complete blog creation, read, update, delete flow', async ({ page }) => {
    test.skip(!password, 'E2E_ADMIN_PASSWORD is required.');

    await page.goto(`${baseUrl}/admin/login`);
    await page.evaluate(() => localStorage.clear());

    await loginThroughAdminUi(page, baseUrl, username, password);
    console.log('✓ Logged in and redirected to dashboard');
    
    // 2. 블로그 페이지로 이동
    await page.goto(`${baseUrl}/admin/blog`);
    await page.waitForTimeout(2000);
    
    // 블로그 목록 표시 대기
    const blogListSelector = '[class*="mud-table"]';
    await page.waitForSelector(blogListSelector, { timeout: 30_000 }).catch(() => null);
    console.log('✓ Blog list page loaded');

    // 3. 새 블로그 포스트 작성
    const createButton = page.getByRole('button', { name: /새|추가|작성/i });
    if (await createButton.isVisible({ timeout: 5_000 }).catch(() => false)) {
      await createButton.click();
      await page.waitForTimeout(1000);
      console.log('✓ Create blog dialog opened');
    }

    // 4. 블로그 목록에서 첫 번째 포스트 확인
    const firstBlogRow = page.locator('tbody tr').first();
    if (await firstBlogRow.isVisible({ timeout: 5_000 }).catch(() => false)) {
      console.log('✓ Blog posts exist in list');
    }

    // 5. 로그아웃 (선택사항)
    const logoutButton = page.getByRole('link', { name: /로그아웃/ });
    if (await logoutButton.isVisible({ timeout: 5_000 }).catch(() => false)) {
      await logoutButton.click();
      console.log('✓ Logout successful');
    }

    console.log('✓ Blog CRUD flow complete');
  });
});
