import { chromium } from '/Users/gbpark/ERP-node/node_modules/playwright/index.mjs';
import { writeFileSync } from 'fs';

const results = [];
let passed = true;
let failReason = '';

async function run() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  try {
    // 로그인
    await page.goto('http://localhost:9771/login');
    await page.waitForLoadState('networkidle');

    await page.getByPlaceholder('사용자 ID를 입력하세요').fill('wace');
    await page.getByPlaceholder('비밀번호를 입력하세요').fill('qlalfqjsgh11');

    await Promise.all([
      page.waitForURL(url => !url.toString().includes('/login'), { timeout: 30000 }),
      page.getByRole('button', { name: '로그인' }).click(),
    ]);
    await page.waitForLoadState('networkidle');
    results.push('✅ 로그인 성공');

    // approvalBox 페이지 접속
    await page.goto('http://localhost:9771/admin/approvalBox');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(3000);
    results.push('✅ approvalBox 페이지 접속 성공');

    // "보낸 결재" 탭 확인
    const sentTabVisible = await page.getByRole('tab', { name: '보낸 결재' }).isVisible().catch(async () => {
      return await page.getByText('보낸 결재').first().isVisible().catch(() => false);
    });
    if (!sentTabVisible) {
      throw new Error('"보낸 결재" 탭이 보이지 않음');
    }
    results.push('✅ "보낸 결재" 탭 확인');

    // 결재 목록 또는 빈 상태 확인
    const rowCount = await page.locator('table tbody tr').count();
    const hasEmpty = await page.getByText(/결재 요청이 없습니다|데이터가 없습니다|없습니다/).isVisible().catch(() => false);
    results.push(`✅ 목록 확인 (rows: ${rowCount}, emptyMsg: ${hasEmpty})`);

    // "받은 결재" 탭 클릭
    const receivedTab = page.getByRole('tab', { name: '받은 결재' });
    const receivedVisible = await receivedTab.isVisible().catch(() => false);
    if (!receivedVisible) {
      throw new Error('"받은 결재" 탭이 보이지 않음');
    }
    await receivedTab.click();
    await page.waitForTimeout(2000);
    results.push('✅ "받은 결재" 탭 클릭');

    // 에러 오버레이 확인
    const hasError = await page.locator('[id="__next"] .nextjs-container-errors-body').isVisible().catch(() => false);
    if (hasError) {
      throw new Error('에러 오버레이 발견');
    }
    results.push('✅ 에러 오버레이 없음');

    // 스크린샷
    await page.screenshot({ path: '/Users/gbpark/ERP-node/.agent-pipeline/browser-tests/result.png', fullPage: true });
    results.push('✅ 스크린샷 저장');

  } catch (err) {
    passed = false;
    failReason = err.message;
    results.push(`❌ 실패: ${err.message}`);
    await page.screenshot({ path: '/Users/gbpark/ERP-node/.agent-pipeline/browser-tests/result-fail.png', fullPage: true }).catch(() => {});
  } finally {
    await browser.close();
  }
}

run().then(() => {
  const output = results.join('\n');
  console.log(output);
  writeFileSync('/tmp/pw-runner-result.txt', output + '\n' + (passed ? 'RESULT: PASS' : `RESULT: FAIL - ${failReason}`));
  console.log(passed ? 'RESULT: PASS' : `RESULT: FAIL - ${failReason}`);
  process.exit(passed ? 0 : 1);
}).catch(err => {
  const msg = `치명적 오류: ${err.message}`;
  console.error(msg);
  writeFileSync('/tmp/pw-runner-result.txt', msg + '\nRESULT: FAIL - ' + err.message);
  process.exit(1);
});
