import { chromium } from "@playwright/test";

(async () => {
  console.log("=== FULL LOGIN FLOW TEST WITH DETAILED LOGGING ===\n");
  
  const b = await chromium.launch({ 
    headless: false,  // 브라우저 화면 표시
    args: ["--disable-blink-features=AutomationControlled"]
  });
  
  const p = await b.newPage();
  
  // 모든 콘솔 메시지 캡처
  p.on("console", msg => {
    const type = msg.type();
    const text = msg.text();
    console.log(`  [BROWSER-${type.toUpperCase()}] ${text}`);
  });
  
  // 모든 요청/응답 로그
  p.on("request", req => {
    if (req.url().includes("auth")) {
      console.log(`  [REQUEST] ${req.method()} ${req.url()}`);
    }
  });
  
  p.on("response", res => {
    if (res.url().includes("auth")) {
      console.log(`  [RESPONSE] ${res.status()} ${res.url()}`);
    }
  });
  
  try {
    console.log("1️⃣  STEP 1: Loading login page...");
    await p.goto("http://localhost:5265/login.html", { waitUntil: "networkidle" });
    console.log("   ✓ Page loaded\n");
    
    console.log("2️⃣  STEP 2: Filling form (admin/admin)...");
    const userInput = await p.$("input[name='username']");
    if (!userInput) {
      console.log("   ✗ Username input NOT FOUND");
      console.log("   Page content snippet:");
      const html = await p.content();
      const snippet = html.substring(0, 500);
      console.log(snippet);
    } else {
      await p.fill("input[name='username']", "admin");
      await p.fill("input[name='password']", "admin");
      console.log("   ✓ Form filled\n");
      
      console.log("3️⃣  STEP 3: Clicking login button...");
      await p.click("button[type='submit']");
      console.log("   ✓ Button clicked\n");
      
      console.log("4️⃣  STEP 4: Waiting 7 seconds for auth flow...");
      for (let i = 1; i <= 7; i++) {
        await new Promise(r => setTimeout(r, 1000));
        const url = p.url();
        console.log(`   [${i}s] Current URL: ${url}`);
      }
      
      console.log("\n5️⃣  FINAL RESULT:");
      const finalUrl = p.url();
      const finalContent = await p.content();
      
      console.log(`   URL: ${finalUrl}`);
      
      if (finalUrl.includes("/dashboard")) {
        if (finalContent.includes("관리자 대시보드")) {
          console.log("   ✓✓✓ SUCCESS! Dashboard loaded with content!");
        } else if (finalContent.includes("Not Found")) {
          console.log("   ✗ Dashboard URL but 'Not Found' error");
        } else {
          console.log("   ✓ Dashboard page (content varies)");
        }
      } else if (finalUrl.includes("/not-found")) {
        console.log("   ✗ FAILED: Redirected to /not-found");
        console.log("   This means authentication failed");
      } else if (finalUrl.includes("/login")) {
        console.log("   ✗ Back at login page");
      } else {
        console.log("   ? Other page");
      }
      
      // 스크린샷 저장
      await p.screenshot({ path: "./playwright-test-result.png", fullPage: true });
      console.log("\n📷 Screenshot saved: playwright-test-result.png");
    }
    
  } catch (e) {
    console.error("❌ Error:", e.message);
  } finally {
    await b.close();
  }
})();
