/**
 * Manual Signup Flow Test
 * Verifies complete signup flow and data persistence
 */

const fetch = require('node-fetch');

const BASE_URL = 'http://localhost:9000';
const TEST_USER = {
  fullName: 'Manual Test User',
  email: `test_${Date.now()}@example.com`,
  password: 'TestPassword123!@#',
  selectedPackage: 'tier2',
};

const COMPANY_INFO = {
  companyName: 'Test Medical Clinic',
  industry: 'healthcare',
  companySize: '11-50',
  gccCountry: 'uae',
  phoneNumber: '+971 50 123 4567',
  agentCount: '5',
  agentUseCase: 'Appointment booking',
  companyDescription: 'Test clinic for automated testing',
  services: ['appointments', 'consultations'],
  selectedPlan: 'tier2',
  billingPeriod: 'monthly',
  currency: 'GBP',
};

async function testSignupFlow() {
  console.log('\n🧪 MANUAL SIGNUP FLOW TEST');
  console.log('═'.repeat(60));

  try {
    // Step 1: Get CSRF Token
    console.log('\n1️⃣  Getting CSRF token...');
    const csrfResponse = await fetch(`${BASE_URL}/api/auth/csrf`);
    const { csrfToken } = await csrfResponse.json();
    console.log(`   ✅ CSRF Token: ${csrfToken.substring(0, 20)}...`);

    // Step 2: Register User
    console.log(`\n2️⃣  Registering user: ${TEST_USER.email}`);
    const registerResponse = await fetch(`${BASE_URL}/api/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken,
      },
      body: JSON.stringify(TEST_USER),
    });

    if (!registerResponse.ok) {
      const error = await registerResponse.json();
      throw new Error(`Registration failed: ${error.error}`);
    }

    const registerData = await registerResponse.json();
    console.log(`   ✅ User registered! User ID: ${registerData.userId}`);
    console.log(`   📝 Selected package: ${TEST_USER.selectedPackage}`);

    // Step 3: Send OTP
    console.log(`\n3️⃣  Sending OTP to ${TEST_USER.email}...`);
    const otpResponse = await fetch(`${BASE_URL}/api/send-otp`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken,
      },
      body: JSON.stringify({ email: TEST_USER.email }),
    });

    if (!otpResponse.ok) {
      const error = await otpResponse.json();
      console.log(`   ⚠️  OTP send result: ${error.error || error.message}`);
    } else {
      console.log(`   ✅ OTP sent successfully`);
    }

    // Step 4: Verify OTP (Development mode uses fixed 123456)
    console.log(`\n4️⃣  Verifying OTP (dev mode: 123456)...`);
    const verifyResponse = await fetch(`${BASE_URL}/api/auth/verify-email-only`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken,
      },
      body: JSON.stringify({
        email: TEST_USER.email,
        otpCode: '123456', // Dev mode fixed OTP
      }),
    });

    if (!verifyResponse.ok) {
      const error = await verifyResponse.json();
      console.log(`   ⚠️  Verification: ${error.error || error.message}`);
    } else {
      console.log(`   ✅ Email verified successfully`);
    }

    // Step 5: Save Company Info
    console.log(`\n5️⃣  Saving company information...`);
    const companyResponse = await fetch(`${BASE_URL}/api/onboarding/company-info`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken,
      },
      body: JSON.stringify({
        email: TEST_USER.email,
        ...COMPANY_INFO,
      }),
    });

    if (!companyResponse.ok) {
      const error = await companyResponse.json();
      console.log(`   ⚠️  Company info: ${error.error || error.message}`);
    } else {
      console.log(`   ✅ Company info saved successfully`);
      console.log(`   📝 Company: ${COMPANY_INFO.companyName}`);
      console.log(`   📝 Industry: ${COMPANY_INFO.industry}`);
      console.log(`   📝 Country: ${COMPANY_INFO.gccCountry}`);
      console.log(`   📝 Services: ${COMPANY_INFO.services.join(', ')}`);
    }

    // Step 6: Verify Data in Database using Supabase REST API
    console.log(`\n6️⃣  Verifying data in database...`);
    const supabaseKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';

    const userCheck = await fetch(
      `http://localhost:54321/rest/v1/users?email=eq.${TEST_USER.email}&select=*`,
      {
        headers: {
          'apikey': supabaseKey,
          'Authorization': `Bearer ${supabaseKey}`,
        },
      }
    );

    if (userCheck.ok) {
      const users = await userCheck.json();
      if (users.length > 0) {
        const user = users[0];
        console.log(`   ✅ User found in database:`);
        console.log(`      - Name: ${user.name}`);
        console.log(`      - Email: ${user.email}`);
        console.log(`      - Email Verified: ${user.emailVerified ? 'Yes' : 'No'}`);
        console.log(`      - Selected Package: ${user.selectedPackage || 'Not set'}`);
        console.log(`      - Company Name: ${user.companyName || 'Not set'}`);
        console.log(`      - Industry: ${user.industry || 'Not set'}`);
        console.log(`      - Phone: ${user.phoneNumber || 'Not set'}`);
        console.log(`      - Country: ${user.country || 'Not set'}`);
        console.log(`      - Onboarding Complete: ${user.onboardingComplete}`);
      } else {
        console.log(`   ⚠️  User not found in database`);
      }
    } else {
      console.log(`   ⚠️  Database query failed`);
    }

    console.log('\n═'.repeat(60));
    console.log('✅ SIGNUP FLOW TEST COMPLETE');
    console.log('═'.repeat(60));

    console.log('\n📊 SUMMARY:');
    console.log(`   User: ${TEST_USER.email}`);
    console.log(`   Password: ${TEST_USER.password}`);
    console.log(`   Package: ${TEST_USER.selectedPackage}`);
    console.log(`   Company: ${COMPANY_INFO.companyName}`);
    console.log('\n💡 You can login with these credentials to verify dashboard access');

  } catch (error) {
    console.error('\n❌ TEST FAILED:', error.message);
    console.error(error);
    process.exit(1);
  }
}

testSignupFlow().catch(console.error);
