#!/usr/bin/env node

const BASE_URL = 'http://localhost:3000';

async function testAutoWorkflow() {
  console.log('🧪 Testing Auto-Workflow...\n');

  console.log('1️⃣ Fetching CONFIRMED bookings...');
  const bookingsRes = await fetch(`${BASE_URL}/api/bookings`);
  const bookingsData = await bookingsRes.json();
  
  const confirmedBookings = bookingsData.bookings.filter(
    (b) => b.status === 'CONFIRMED' && !b.tourId
  );
  
  console.log(`   ✅ Found ${confirmedBookings.length} CONFIRMED bookings without tour:`);
  confirmedBookings.forEach((b) => {
    console.log(`      - ${b.bookingNumber}: ${b.customerName} (${new Date(b.eventDate).toLocaleDateString('de-DE')})`);
  });

  if (confirmedBookings.length === 0) {
    console.log('   ⚠️  No bookings to process. Auto-workflow test skipped.');
    return;
  }

  console.log('\n2️⃣ Creating tour for CONFIRMED bookings...');
  
  const bookingIds = confirmedBookings.map((b) => b.id);
  const tourDate = confirmedBookings[0].eventDate;

  const tourRes = await fetch(`${BASE_URL}/api/tours`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      tourDate,
      bookingIds,
    }),
  });

  if (!tourRes.ok) {
    const error = await tourRes.json();
    console.log(`   ❌ Tour creation failed: ${error.error}`);
    return;
  }

  const tourData = await tourRes.json();
  console.log(`   ✅ Tour created: ${tourData.tour.tourNumber}`);
  console.log(`      - Status: ${tourData.tour.status}`);
  console.log(`      - Bookings: ${tourData.tour.bookings?.length || 0}`);
  console.log(`      - Total Distance: ${tourData.tour.totalDistance || 'N/A'} km`);
  console.log(`      - Estimated Duration: ${tourData.tour.estimatedDuration || 'N/A'} min`);

  console.log('\n3️⃣ Verifying tour assignment...');
  const updatedBookingsRes = await fetch(`${BASE_URL}/api/bookings`);
  const updatedBookingsData = await updatedBookingsRes.json();
  
  const tourAssignedCount = updatedBookingsData.bookings.filter(
    (b) => b.tourId === tourData.tour.id
  ).length;

  console.log(`   ✅ ${tourAssignedCount}/${bookingIds.length} bookings assigned to tour`);

  console.log('\n4️⃣ Testing Nextcloud Calendar Sync...');
  try {
    const syncRes = await fetch(`${BASE_URL}/api/calendar/sync`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ 
        action: 'sync-booking',
        bookingId: confirmedBookings[0].id 
      }),
    });

    const syncData = await syncRes.json();
    if (syncData.success) {
      console.log(`   ✅ Calendar sync successful for booking ${confirmedBookings[0].bookingNumber}`);
    } else {
      console.log(`   ⚠️  Calendar sync failed: ${syncData.error}`);
    }
  } catch (error) {
    console.log(`   ⚠️  Calendar sync error: ${error.message}`);
  }

  console.log('\n✅ Auto-Workflow Test Complete!\n');
}

async function testNextcloudConnection() {
  console.log('🔌 Testing Nextcloud Connection...\n');

  try {
    const res = await fetch(`${BASE_URL}/api/calendar/sync`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'test-connection' }),
    });

    const data = await res.json();
    
    if (data.success) {
      console.log('   ✅ Nextcloud connection successful!');
      console.log(`   📅 Found ${data.calendars?.length || 0} calendar(s):`);
      data.calendars?.forEach((cal) => {
        console.log(`      - ${cal.displayName}`);
      });
    } else {
      console.log('   ❌ Nextcloud connection failed:');
      console.log(`      ${data.error}`);
    }
  } catch (error) {
    console.log(`   ❌ Connection error: ${error.message}`);
  }

  console.log('');
}

async function runTests() {
  console.log('╔════════════════════════════════════════════════╗');
  console.log('║  SaveTheMoment Atlas - Auto-Workflow Test     ║');
  console.log('╚════════════════════════════════════════════════╝\n');

  await testNextcloudConnection();
  await testAutoWorkflow();

  console.log('Done! 🎉\n');
}

runTests().catch(console.error);
