const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');

const screenshotsDir = path.join(__dirname, 'test-screenshots');
if (!fs.existsSync(screenshotsDir)) {
  fs.mkdirSync(screenshotsDir, { recursive: true });
}

let screenshotCount = 0;

async function takeScreenshot(page, name) {
  screenshotCount++;
  const num = screenshotCount.toString().padStart(2, '0');
  const filename = num + '-' + name + '.png';
  const filepath = path.join(screenshotsDir, filename);
  await page.screenshot({ path: filepath, fullPage: true });
  console.log('Screenshot: ' + filename);
  return filepath;
}

async function runTest() {
  let browser;
  try {
    console.log('\n========== PLAYWRIGHT TEST START ==========\n');
    
    browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    // Step 1
    console.log('STEP 1: Load application at localhost:3000');
    await page.goto('http://localhost:3000', { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(2000);
    await takeScreenshot(page, 'step1-initial-page');
    console.log('- Application loaded');
    
    // Step 2: Click "수주관리"
    console.log('\nSTEP 2: Click on "수주관리" menu');
    const salesOrderBtn = await page.locator('button:has-text("수주관리")').first();
    if (await salesOrderBtn.count() > 0) {
      await salesOrderBtn.click();
      console.log('- Clicked "수주관리" button');
      await page.waitForTimeout(2000);
      await takeScreenshot(page, 'step2-after-menu-click');
    } else {
      console.log('ERROR: Could not find "수주관리" button');
    }
    
    // Step 3: Find C-grade customer order
    console.log('\nSTEP 3: Looking for C-grade customer order (한화시공)');
    const pageText = await page.textContent('body');
    
    if (pageText.includes('한화시공')) {
      console.log('- Found "한화시공" customer');
      const hwLink = await page.locator('text=한화시공').first();
      await hwLink.click();
      console.log('- Clicked on order containing "한화시공"');
      await page.waitForTimeout(2000);
      await takeScreenshot(page, 'step3-found-customer');
    } else {
      console.log('- "한화시공" not found in current view');
      
      // Try to find any customer links
      const allText = await page.textContent('body');
      console.log('- Searching for customer orders in page...');
      
      const rows = await page.locator('table tbody tr, [class*="row"]').all();
      console.log('- Found ' + rows.length + ' rows');
      
      if (rows.length > 0) {
        await rows[0].click();
        console.log('- Clicked first order row');
        await page.waitForTimeout(2000);
        await takeScreenshot(page, 'step3-first-order');
      }
    }
    
    // Step 4: Look for "생산지시" button
    console.log('\nSTEP 4: Looking for "생산지시" button');
    const prodButton = await page.locator('button:has-text("생산지시")').first();
    
    if (await prodButton.count() > 0) {
      console.log('- Found "생산지시" button');
      
      // Check if button is disabled (requires approval)
      const isDisabled = await prodButton.isDisabled();
      if (isDisabled) {
        console.log('- Button is DISABLED (requires approval)');
      } else {
        console.log('- Button is ENABLED (no approval required)');
      }
      
      await takeScreenshot(page, 'step4-found-production-button');
      
      if (!isDisabled) {
        console.log('- Attempting to click "생산지시" button...');
        await prodButton.click();
        await page.waitForTimeout(2000);
        await takeScreenshot(page, 'step4-after-click-production');
        
        // Check for success message
        const successMsg = await page.locator('[class*="success"], [class*="toast"], [role="status"]').textContent();
        if (successMsg) {
          console.log('- Success message: ' + successMsg);
        }
      }
    } else {
      console.log('- "생산지시" button not found');
      
      // List all available buttons
      const allButtons = await page.locator('button').all();
      console.log('- Available buttons:');
      for (let i = 0; i < Math.min(15, allButtons.length); i++) {
        const text = await allButtons[i].textContent();
        if (text && text.trim().length > 0) {
          console.log('  * ' + text.trim());
        }
      }
    }
    
    // Step 5: Final status check
    console.log('\nSTEP 5: Final status check');
    
    // Check for any error messages
    const errorElements = await page.locator('[class*="error"], [role="alert"], [class*="alert"]').all();
    if (errorElements.length > 0) {
      for (let el of errorElements) {
        const text = await el.textContent();
        if (text && text.length > 0) {
          console.log('- Alert message: ' + text);
        }
      }
    }
    
    await takeScreenshot(page, 'step5-final-status');
    console.log('- Final status captured');
    
    await context.close();
    await browser.close();
    
    console.log('\n========== TEST COMPLETED ==========');
    console.log('Screenshots saved to: ' + screenshotsDir);
    console.log('Total screenshots: ' + screenshotCount);
    
  } catch (error) {
    console.error('\nERROR during test:');
    console.error('Message: ' + error.message);
    console.error('Stack: ' + error.stack);
    if (browser) await browser.close();
    process.exit(1);
  }
}

runTest();
