/**
 * Test the complete CSV booking workflow
 * This tests if email sending is triggered when creating a booking
 */

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const API_BASE = 'http://localhost:4000/api/v1';

// Test credentials - you need to use real credentials from your database
const TEST_USER = {
  email: 'admin@xpeditis.com', // Change this to a real user email
  password: 'Admin123!', // Change this to the real password
};

async function testWorkflow() {
  console.log('🧪 Testing CSV Booking Workflow\n');

  try {
    // Step 1: Login to get JWT token
    console.log('1️⃣ Logging in...');
    const loginResponse = await axios.post(`${API_BASE}/auth/login`, {
      email: TEST_USER.email,
      password: TEST_USER.password,
    });

    const token = loginResponse.data.accessToken;
    console.log('✅ Login successful\n');

    // Step 2: Create a test CSV booking
    console.log('2️⃣ Creating CSV booking...');

    const form = new FormData();

    // Booking data
    form.append('carrierName', 'Test Carrier');
    form.append('carrierEmail', 'test-carrier@example.com'); // Email to receive booking
    form.append('origin', 'FRPAR');
    form.append('destination', 'USNYC');
    form.append('volumeCBM', '10');
    form.append('weightKG', '500');
    form.append('palletCount', '2');
    form.append('priceUSD', '1500');
    form.append('priceEUR', '1300');
    form.append('primaryCurrency', 'USD');
    form.append('transitDays', '15');
    form.append('containerType', '20FT');
    form.append('notes', 'Test booking for email workflow verification');

    // Create a test document file
    const testDocument = Buffer.from('Test document content for booking');
    form.append('documents', testDocument, {
      filename: 'test-invoice.pdf',
      contentType: 'application/pdf',
    });

    const bookingResponse = await axios.post(`${API_BASE}/csv-bookings`, form, {
      headers: {
        ...form.getHeaders(),
        Authorization: `Bearer ${token}`,
      },
    });

    console.log('✅ Booking created successfully!');
    console.log('📦 Booking ID:', bookingResponse.data.id);
    console.log('📧 Email should be sent to:', bookingResponse.data.carrierEmail);
    console.log('🔗 Confirmation token:', bookingResponse.data.confirmationToken);
    console.log('\n💡 Check backend logs for:');
    console.log('   - "Email sent to carrier: test-carrier@example.com"');
    console.log('   - "CSV booking request sent to test-carrier@example.com"');
    console.log('   - OR any error messages about email sending');
    console.log('\n📬 Check Mailtrap inbox: https://mailtrap.io/inboxes');
  } catch (error) {
    console.error('❌ Error:', error.response?.data || error.message);

    if (error.response?.status === 401) {
      console.error(
        '\n⚠️  Authentication failed. Please update TEST_USER credentials in the script.'
      );
    }

    if (error.response?.status === 400) {
      console.error('\n⚠️  Bad request. Check the booking data format.');
      console.error('Details:', error.response.data);
    }

    if (error.code === 'ECONNREFUSED') {
      console.error('\n⚠️  Backend server is not running. Start it with: npm run backend:dev');
    }
  }
}

testWorkflow();
