import { test, expect } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';

test.describe('QE-M3-05: Scores Database DOM Verification', () => {
  // Login before each test
  test.beforeEach(async ({ page }) => {
    await page.goto('/Account/Login');
    await page.waitForLoadState('domcontentloaded');

    // Fill login form with credentials (admin/quant123! — see CLAUDE.md)
    const usernameInput = page.locator('#username');
    const passwordInput = page.locator('#password');
    const loginButton = page.locator('#loginBtn');

    await usernameInput.fill('admin');
    await passwordInput.fill('quant123!');
    await loginButton.click();

    // Wait strictly for dashboard redirect to confirm session cookie is active
    await page.waitForURL('**/Admin/**');
  });

  test('QE-M3-05: Table viewer displays engine_history.factor_output_history values in DOM', async ({ page }) => {
    console.log('\n=== QE-M3-05 Test Started ===');

    // Step 1: Navigate to Database Table Viewer admin page
    await page.goto('/Admin/Database');
    await page.waitForLoadState('domcontentloaded');

    // Step 2: Verify page title
    const pageTitle = await page.title();
    expect(pageTitle).toContain('DB 테이블 관리');
    console.log('✓ Database admin page loaded successfully');

    // Step 3: Locate and click "engine_history.factor_output_history" from table list
    const factorTableLink = page.locator('a.list-group-item:has-text("factor_output_history")');
    await expect(factorTableLink).toBeVisible();
    await factorTableLink.click();
    await page.waitForLoadState('domcontentloaded');
    console.log('✓ Clicked on engine_history.factor_output_history');

    // Step 4: Verify table data is visible
    const tableHeader = page.locator('h3.card-title:has-text("engine_history.factor_output_history 데이터 조회")');
    await expect(tableHeader).toBeVisible();

    // Step 5: Check if our mock factor composite data from QE-M3-03 exists in DOM
    const compositeCell = page.locator('span:has-text("SS001_COMPOSITE_FACTOR_")').first();
    await expect(compositeCell).toBeVisible();
    
    const compositeText = await compositeCell.textContent();
    console.log(`✓ Found ingested factor record in DOM: ${compositeText}`);

    // Step 6: Create screenshot directory and save screenshot
    const screenshotDir = path.join(process.cwd(), 'Temp', 'evidence', 'QE-M3-05', 'screenshots');
    fs.mkdirSync(screenshotDir, { recursive: true });

    await page.screenshot({
      path: path.join(screenshotDir, '01-scores-tab.png'),
      fullPage: true,
    });
    console.log(`✓ E2E Screenshot saved: 01-scores-tab.png`);

    console.log('=== QE-M3-05 Test Completed Successfully ===\n');
  });
});
