const { google } = require('googleapis');
const { v4: uuidv4 } = require('uuid');

/**
 * Google Meet Integration Utility
 * 
 * Two approaches:
 * 1. Simple Meet Links (no API required) - RECOMMENDED for quick setup
 * 2. Google Calendar API with Meet (requires service account)
 */

/**
 * Generate a working Meet link using instant meeting approach
 * This provides multiple options for video conferencing
 */
const generateSimpleMeetLink = () => {
  // Use timestamp + random for uniqueness
  const timestamp = Date.now().toString(36);
  const random = Math.random().toString(36).substring(2, 8);
  
  // Create a unique meeting room identifier
  const meetingId = `therapy-${timestamp}-${random}`;
  
  return {
    meetLink: `https://meet.google.com/new`, // Creates instant meeting
    jitsiLink: `https://meet.jit.si/${meetingId}`, // Backup option
    zoomPersonalRoom: `https://zoom.us/my/mendingmind`, // If you have Zoom
    meetingId: meetingId,
    instructions: "Primary: Click Google Meet link to start instant meeting. Backup: Use Jitsi link if Google Meet has issues."
  };
};

/**
 * Generate Google Calendar event with Meet link
 * Requires Google Calendar API setup with service account
 */
const generateCalendarMeetLink = async (appointmentDetails) => {
  try {
    // Check if Google credentials are configured
    if (!process.env.GOOGLE_SERVICE_ACCOUNT_KEY) {
      console.log("Google Calendar API not configured, using simple Meet link");
      return generateSimpleMeetLink();
    }

    // Parse service account credentials
    const credentials = JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_KEY);
    
    // Create JWT auth
    const auth = new google.auth.JWT(
      credentials.client_email,
      null,
      credentials.private_key,
      ['https://www.googleapis.com/auth/calendar']
    );

    const calendar = google.calendar({ version: 'v3', auth });

    // Create calendar event with Meet link
    const event = {
      summary: `Therapy Session - ${appointmentDetails.patientName}`,
      description: `Online therapy session between ${appointmentDetails.doctorName} and ${appointmentDetails.patientName}`,
      start: {
        dateTime: appointmentDetails.startDateTime,
        timeZone: 'Asia/Kolkata', // Adjust as needed
      },
      end: {
        dateTime: appointmentDetails.endDateTime,
        timeZone: 'Asia/Kolkata',
      },
      attendees: [
        { email: appointmentDetails.doctorEmail },
        { email: appointmentDetails.patientEmail },
      ],
      conferenceData: {
        createRequest: {
          requestId: uuidv4(),
          conferenceSolutionKey: {
            type: 'hangoutsMeet'
          }
        }
      },
      reminders: {
        useDefault: false,
        overrides: [
          { method: 'email', minutes: 24 * 60 }, // 1 day before
          { method: 'popup', minutes: 30 }, // 30 minutes before
        ],
      },
    };

    const response = await calendar.events.insert({
      calendarId: 'primary',
      resource: event,
      conferenceDataVersion: 1,
    });

    const meetLink = response.data.conferenceData?.entryPoints?.find(
      entry => entry.entryPointType === 'video'
    )?.uri;

    return {
      meetLink: meetLink || generateSimpleMeetLink().meetLink,
      eventId: response.data.id,
      calendarLink: response.data.htmlLink,
      instructions: "Join the Google Meet session using the link below"
    };

  } catch (error) {
    console.error('Error creating calendar event with Meet:', error);
    // Fallback to simple Meet link
    return generateSimpleMeetLink();
  }
};

/**
 * Main function to generate REAL WORKING Google Meet links
 * Uses Google Calendar API to create actual Meet rooms
 */
const generateMeetLinkForAppointment = async (appointmentData) => {
  const { ProperGoogleMeet } = require('./properGoogleMeet');
  
  try {
    console.log('🚀 Creating PROPER Google Meet room for appointment...');
    
    const properMeet = new ProperGoogleMeet();
    const result = await properMeet.createProperMeetRoom(appointmentData);
    
    console.log('✅ PROPER Google Meet room created successfully');
    
    return { 
      meetLink: result.meetLink,
      meetingCode: result.meetingCode,
      meetingId: result.meetingCode,
      instructions: `Join your therapy session: ${result.meetLink}`,
      type: result.type,
      persistent: result.persistent,
      success: result.success,
      eventId: result.eventId,
      calendarLink: result.calendarLink,
      conferenceId: result.conferenceId,
      calendarInviteSent: result.calendarInviteSent
    };
    
  } catch (error) {
    console.error('❌ Error creating proper Meet room, using fallback:', error);
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).substring(2, 8);
    const roomId = `therapy-emergency-${timestamp}-${random}`;
    return {
      meetLink: `https://meet.jit.si/${roomId}`,
      meetingId: roomId,
      meetingCode: roomId,
      instructions: 'Emergency video room using Jitsi Meet (always reliable)',
      type: 'emergency-jitsi',
      persistent: true,
      success: true,
      error: `Google Meet creation failed: ${error.message}`
    };
  }
};

module.exports = {
  generateMeetLinkForAppointment,
  generateSimpleMeetLink,
  generateCalendarMeetLink
};
