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

test.describe('QE-M2-05: Price History Summary Tab 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 for login to complete
    await page.waitForLoadState('domcontentloaded');
  });

  test('QE-M2-05: History tab renders with API-derived ticker data', async ({ page }) => {
    // Step 1: Fetch expected values from API (source of truth)
    const apiResponse = await page.request.get('/api/collection/history-summary');
    expect(apiResponse.ok()).toBeTruthy();

    const responseJson = await apiResponse.json();
    const tickers = (responseJson as any).tickers || [];

    // Fail if no price history data exists
    if (tickers.length === 0) {
      throw new Error(
        'No price_history_daily rows in DB — run collection with price-history persistence first. ' +
        'Expected at least 1 ticker in price_history_daily table.'
      );
    }

    // Extract expected values from first ticker
    const expectedTicker = tickers[0];
    const expectedTickerValue = expectedTicker.ticker;
    const expectedRowCount = expectedTicker.rowCount;
    const expectedFirstDate = expectedTicker.firstDate;
    const expectedLastDate = expectedTicker.lastDate;

    console.log(
      `\n=== QE-M2-05 Test Started ===\n` +
      `Expected Ticker: ${expectedTickerValue}\n` +
      `Expected RowCount: ${expectedRowCount}\n` +
      `Expected FirstDate: ${expectedFirstDate}\n` +
      `Expected LastDate: ${expectedLastDate}\n`
    );

    // Step 2: Navigate to Collection admin page
    await page.goto('/Admin/Collection');
    await page.waitForLoadState('domcontentloaded');

    // Step 3: Verify page title contains "데이터 수집" (collection)
    const pageTitle = await page.title();
    expect(pageTitle).toContain('데이터 수집');

    // Step 4: Verify history section is visible
    const historyCard = page.locator('h3.card-title:has-text("히스토리 현황")');
    await expect(historyCard).toBeVisible();
    console.log('✓ History card section found and visible');

    // Step 5: Verify the table contains a row with expected ticker
    const tickerCell = page.locator(`td:has-text("${expectedTickerValue}")`).first();
    await expect(tickerCell).toBeVisible();
    console.log(`✓ Ticker row found: ${expectedTickerValue}`);

    // Step 6: Find the row and verify row count matches
    const tableRow = tickerCell.locator('xpath=ancestor::tr');
    const cells = tableRow.locator('td');
    const cellCount = await cells.count();
    expect(cellCount).toBeGreaterThanOrEqual(4); // At least 4 columns (ticker, row count, first date, last date)

    // Cell 1 (index 1) is "데이터 수" (row count)
    const rowCountCell = cells.nth(1);
    const rowCountText = await rowCountCell.textContent();
    expect(rowCountText?.trim()).toBe(String(expectedRowCount));
    console.log(`✓ Row count matches: ${rowCountText?.trim()} == ${expectedRowCount}`);

    // Cell 2 (index 2) is "시작일" (first date)
    const firstDateCell = cells.nth(2);
    const firstDateText = await firstDateCell.textContent();
    expect(firstDateText?.trim()).toContain(expectedFirstDate);
    console.log(`✓ First date matches: ${firstDateText?.trim()} contains ${expectedFirstDate}`);

    // Cell 3 (index 3) is "종료일" (last date)
    const lastDateCell = cells.nth(3);
    const lastDateText = await lastDateCell.textContent();
    expect(lastDateText?.trim()).toContain(expectedLastDate);
    console.log(`✓ Last date matches: ${lastDateText?.trim()} contains ${expectedLastDate}`);

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

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

    console.log(
      `\n=== QE-M2-05 Test Completed Successfully ===\n` +
      `Evidence files saved to: ${screenshotDir}\n`
    );
  });
});
