import { BookingData, Vehicle } from "../types/booking";

// Mock email service for demonstration
const mockEmailService = async (bookingData: BookingData, selectedVehicle: Vehicle) => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  // Generate a mock booking ID
  const bookingId = `SNG${Date.now().toString().slice(-6)}`;
  
  // Log booking details for development
  console.log('Booking Details:', {
    bookingId,
    customer: {
      name: bookingData.contactName,
      // phone: bookingData.phone,
      pickup: bookingData.pickup,
      dropoff: bookingData.dropoff,
      date: bookingData.date,
      time: bookingData.time
    },
    vehicle: {
      type: selectedVehicle.type,
      price: selectedVehicle.price,
      estimatedTime: selectedVehicle.estimatedTime
    }
  });
  
  // Simulate 95% success rate
  if (Math.random() > 0.05) {
    return { success: true, bookingId };
  } else {
    throw new Error('Mock email service unavailable');
  }
};

export async function confirmBooking(
  bookingData: BookingData, 
  selectedVehicle: Vehicle
): Promise<{ success: boolean; error?: string; message?: string; bookingId?: string }> {
  try {
    const result = await mockEmailService(bookingData, selectedVehicle);
    
    if (result.success) {
      console.log('Booking confirmed successfully:', result.bookingId);
      return { success: true, bookingId: result.bookingId };
    } else {
      return { 
        success: false, 
        error: 'SERVICE_ERROR',
        message: 'Booking service temporarily unavailable' 
      };
    }
  } catch (error) {
    console.error('Error confirming booking:', error);
    return { 
      success: false, 
      error: 'NETWORK_ERROR',
      message: `Network error: ${error instanceof Error ? error.message : 'Unknown error'}` 
    };
  }
}

export function handleBookingError(error?: string): void {
  // Show user-friendly error message but still proceed to success
  if (error === 'SERVICE_ERROR') {
    alert('Booking saved! However, the booking service is temporarily unavailable. You will be contacted directly at your provided phone number.');
  } else if (error === 'NETWORK_ERROR') {
    alert('Booking confirmed! There was a minor network issue, but your booking is saved and you will be contacted directly.');
  } else {
    alert('Booking confirmed! Your booking has been processed and you will be contacted directly.');
  }
}