#!/usr/bin/env node
/**
 * Nxtgauge E2E Company Verification Flow - Guided Manual Test
 *
 * This script helps guide you through the complete end-to-end test:
 * 1. Creates a test company account
 * 2. Fills company profile
 * 3. Submits for verification
 * 4. Verifies in admin panel
 *
 * Usage:
 *   node manual-e2e-test.cjs
 *
 * The script will open browsers and provide step-by-step instructions.
 */

const { chromium } = require("playwright");
const { randomUUID } = require("crypto");
const fs = require("fs");
const path = require("path");

// Test data
const testData = {
  firstName: "John",
  lastName: "Doe",
  email: `testcompany${randomUUID().slice(0, 8)}@test.com`,
  password: "TestPassword123!",
  companyName: `Test Company ${randomUUID().slice(0, 6)}`,
  phone: "+91 9876543210",
  website: "https://testcompany.com",
  address: "123 Tech Park, Bangalore, Karnataka 560001",
};

// Save test data for reference
const testDataPath = path.join(__dirname, "test-data.json");
fs.writeFileSync(testDataPath, JSON.stringify(testData, null, 2));

console.log("\n" + "=".repeat(70));
console.log("  NXTGAUGE E2E COMPANY VERIFICATION FLOW - GUIDED TEST");
console.log("=".repeat(70));
console.log("\n📋 Test Data (saved to test-data.json):");
console.log(`   First Name: ${testData.firstName}`);
console.log(`   Last Name:  ${testData.lastName}`);
console.log(`   Email:      ${testData.email}`);
console.log(`   Password:   ${testData.password}`);
console.log(`   Company:    ${testData.companyName}`);
console.log("\n" + "-".repeat(70));

async function runTest() {
  let browser;
  let adminBrowser;

  try {
    // Step 1: Open Signup Page
    console.log("\n🚀 STEP 1: Opening Signup Page");
    console.log("   URL: http://localhost:3001/signup?intent=company");

    browser = await chromium.launch({
      headless: false,
      slowMo: 100,
    });

    const context = await browser.newContext({
      viewport: { width: 1400, height: 900 },
    });

    const page = await context.newPage();
    await page.goto("http://localhost:3001/signup?intent=company");
    await page.waitForLoadState("networkidle");

    console.log("   ✓ Signup page loaded\n");

    // Step 2: Fill Signup Form
    console.log("📝 STEP 2: Filling Signup Form");
    await page.fill("#first-name", testData.firstName);
    console.log("   ✓ First Name");

    await page.fill("#last-name", testData.lastName);
    console.log("   ✓ Last Name");

    await page.fill("#email", testData.email);
    console.log("   ✓ Email:", testData.email);

    await page.fill("#password", testData.password);
    console.log("   ✓ Password");

    await page.fill("#confirm-password", testData.password);
    console.log("   ✓ Confirm Password");

    await page.check('input[type="checkbox"]');
    console.log("   ✓ Terms & Conditions");

    console.log("\n⚠️  ACTION REQUIRED:");
    console.log("   Please enter the CAPTCHA code shown on the page.");
    console.log("   The Sign Up button will become active once valid.");
    console.log("   Click the Sign Up button after entering CAPTCHA.");

    // Wait for user to complete signup and OTP verification
    console.log("\n⏳ Waiting for signup and email verification to complete...");
    console.log("   (The page should redirect to login after OTP verification)");

    // Wait for navigation to login page
    await page.waitForURL("**/login**", { timeout: 300000 });
    console.log("   ✓ Email verified and redirected to login\n");

    // Step 3: Login
    console.log("🔐 STEP 3: Logging In");
    await page.fill('input[type="email"]', testData.email);
    await page.fill('input[type="password"]', testData.password);
    await page.click('button[type="submit"]');

    await page.waitForTimeout(3000);
    console.log("   ✓ Logged in successfully\n");

    // Step 4: Check for Company Profile Setup
    console.log("🏢 STEP 4: Company Profile Setup");
    console.log("   Looking for company profile or onboarding flow...");

    // Take screenshot of current state
    await page.screenshot({ path: "./test-results/04-after-login.png", fullPage: true });

    // Check if there's a profile setup form
    const currentUrl = page.url();
    console.log(`   Current URL: ${currentUrl}`);

    if (currentUrl.includes("profile") || currentUrl.includes("onboarding")) {
      console.log("   Profile setup page detected");

      // Try to fill company profile
      const nameInput = await page.locator('input[name="name"], input[name="companyName"]').first();
      if (await nameInput.isVisible().catch(() => false)) {
        await nameInput.fill(testData.companyName);
        console.log("   ✓ Company name filled");
      }

      const websiteInput = await page.locator('input[name="website"]').first();
      if (await websiteInput.isVisible().catch(() => false)) {
        await websiteInput.fill(testData.website);
        console.log("   ✓ Website filled");
      }

      const phoneInput = await page.locator('input[name="phone"]').first();
      if (await phoneInput.isVisible().catch(() => false)) {
        await phoneInput.fill(testData.phone);
        console.log("   ✓ Phone filled");
      }

      const addressInput = await page
        .locator('textarea[name="address"], input[name="address"]')
        .first();
      if (await addressInput.isVisible().catch(() => false)) {
        await addressInput.fill(testData.address);
        console.log("   ✓ Address filled");
      }

      console.log("\n⚠️  ACTION REQUIRED:");
      console.log("   Please review and submit the company profile form.");
      console.log("   Click any Submit/Save button to complete profile setup.");

      // Wait for submission
      await page.waitForTimeout(10000);
    } else {
      console.log("   ℹ️ No profile setup page detected (may be dashboard-first flow)");
    }

    await page.screenshot({ path: "./test-results/05-company-profile.png", fullPage: true });
    console.log("   ✓ Company profile step completed\n");

    // Step 5: Open Admin Panel
    console.log("🔐 STEP 5: Opening Admin Panel");
    console.log("   URL: http://localhost:3000/login");

    adminBrowser = await chromium.launch({
      headless: false,
      slowMo: 100,
    });

    const adminContext = await adminBrowser.newContext({
      viewport: { width: 1400, height: 900 },
    });

    const adminPage = await adminContext.newPage();
    await adminPage.goto("http://localhost:3000/login");
    await adminPage.waitForLoadState("networkidle");

    // Admin login
    await adminPage.fill('input[type="email"]', "admin@nxtgauge.com");
    await adminPage.fill('input[type="password"]', "admin123");
    await adminPage.click('button[type="submit"]');

    await adminPage.waitForTimeout(3000);
    console.log("   ✓ Admin logged in\n");

    await adminPage.screenshot({ path: "./test-results/06-admin-dashboard.png", fullPage: true });

    // Step 6: Navigate to Verifications
    console.log("🔍 STEP 6: Checking Verification Queue");

    // Try to find and click Verifications link
    const verificationSelectors = [
      "text=Verifications",
      'a:has-text("Verification")',
      '[href*="verification"]',
      "text=Pending",
      "text=Companies",
    ];

    let found = false;
    for (const selector of verificationSelectors) {
      const link = await adminPage.locator(selector).first();
      if (await link.isVisible().catch(() => false)) {
        console.log(`   Found navigation: ${selector}`);
        await link.click();
        found = true;
        break;
      }
    }

    if (!found) {
      console.log("   ⚠️ Could not find Verifications link automatically");
      console.log("   Please navigate to the Verifications section manually.");
    }

    await adminPage.waitForTimeout(3000);
    await adminPage.screenshot({ path: "./test-results/07-verification-list.png", fullPage: true });

    // Step 7: Search for our company
    console.log("\n🔎 STEP 7: Searching for Test Company");
    console.log(`   Email: ${testData.email}`);

    const searchInput = await adminPage
      .locator('input[type="search"], input[placeholder*="search" i]')
      .first();
    if (await searchInput.isVisible().catch(() => false)) {
      await searchInput.fill(testData.email);
      await adminPage.waitForTimeout(2000);
      console.log("   ✓ Search performed");
    } else {
      console.log("   ℹ️ No search input found - please search manually");
    }

    await adminPage.screenshot({ path: "./test-results/08-search-results.png", fullPage: true });

    // Check if company appears
    const pageContent = await adminPage.locator("body").innerText();
    const companyFound =
      pageContent.includes(testData.email) || pageContent.includes(testData.companyName);

    console.log("\n" + "=".repeat(70));
    if (companyFound) {
      console.log("  ✅ SUCCESS: Company found in verification queue!");
    } else {
      console.log("  ⚠️ Company not immediately visible in verification queue");
      console.log("     This may be expected - check:");
      console.log("     1. Different verification section");
      console.log("     2. Filters applied to the list");
      console.log("     3. Company profile not yet submitted for verification");
    }
    console.log("=".repeat(70));

    console.log("\n📋 Test Summary:");
    console.log(`   Email:      ${testData.email}`);
    console.log(`   Password:   ${testData.password}`);
    console.log(`   Company:    ${testData.companyName}`);
    console.log("\n📸 Screenshots saved to: ./test-results/");
    console.log("📝 Test data saved to: ./test-data.json");
    console.log("\n✅ Test flow completed!");
    console.log("   Both browser windows are open for your review.");
    console.log("   Close the browsers when done.\n");

    // Keep browsers open
    await new Promise(() => {});
  } catch (error) {
    console.error("\n❌ Test error:", error.message);
    console.log("\n📸 Check screenshots in ./test-results/ for debugging");
    throw error;
  }
}

// Run the test
runTest().catch(console.error);
