const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
require('dotenv').config();

class ProperGoogleMeet {
  constructor() {
    this.oauth2Client = null;
    this.calendar = null;
    this.meet = null;
  }

  /**
   * Initialize with OAuth credentials
   */
  async initialize() {
    try {
      const clientId = process.env.GOOGLE_OAUTH_CLIENT_ID;
      const clientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;
      
      if (!clientId || !clientSecret) {
        throw new Error('OAuth credentials not configured');
      }

      this.oauth2Client = new OAuth2Client(clientId, clientSecret);
      
      // Set credentials if we have them
      if (process.env.GOOGLE_OAUTH_ACCESS_TOKEN) {
        this.oauth2Client.setCredentials({
          access_token: process.env.GOOGLE_OAUTH_ACCESS_TOKEN,
          refresh_token: process.env.GOOGLE_OAUTH_REFRESH_TOKEN
        });
        
        this.calendar = google.calendar({ version: 'v3', auth: this.oauth2Client });
        console.log('✅ Google Meet API initialized with OAuth');
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('❌ Failed to initialize Google Meet API:', error.message);
      return false;
    }
  }

  /**
   * Create a proper Google Meet room using Calendar API
   * This creates actual persistent Meet rooms with proper URLs
   */
  async createProperMeetRoom(appointmentDetails) {
    if (!this.calendar) {
      const initialized = await this.initialize();
      if (!initialized) {
        throw new Error('Google Meet API not initialized. Please complete OAuth flow.');
      }
    }

    try {
      const { 
        patientName, 
        patientEmail, 
        doctorName, 
        doctorEmail, 
        startDateTime, 
        endDateTime 
      } = appointmentDetails;

      console.log('🚀 Creating PROPER Google Meet room...');

      // Create unique request ID for the conference
      const requestId = `therapy-proper-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;

      // Create calendar event with Google Meet conference
      const event = {
        summary: `Therapy Session: ${patientName} & Dr. ${doctorName}`,
        description: `Confidential therapy session between ${patientName} and Dr. ${doctorName}.\n\nThis is a private medical consultation.`,
        
        start: {
          dateTime: startDateTime,
          timeZone: process.env.TIMEZONE || 'Asia/Kolkata',
        },
        end: {
          dateTime: endDateTime,
          timeZone: process.env.TIMEZONE || 'Asia/Kolkata',
        },
        
        // Add attendees
        attendees: [
          { 
            email: doctorEmail,
            displayName: `Dr. ${doctorName}`
          },
          { 
            email: patientEmail,
            displayName: patientName
          }
        ],
        
        // THIS IS THE KEY: conferenceData creates the actual Meet room
        conferenceData: {
          createRequest: {
            requestId: requestId,
            conferenceSolutionKey: {
              type: 'hangoutsMeet'
            }
          }
        },
        
        reminders: {
          useDefault: false,
          overrides: [
            { method: 'email', minutes: 1440 }, // 24 hours
            { method: 'email', minutes: 60 },   // 1 hour
            { method: 'popup', minutes: 15 },   // 15 minutes
          ],
        },
        
        guestsCanInviteOthers: false,
        guestsCanModify: false,
        guestsCanSeeOtherGuests: true,
      };

      // Insert the event with conference data
      const response = await this.calendar.events.insert({
        calendarId: 'primary',
        resource: event,
        conferenceDataVersion: 1,
        sendUpdates: 'all' // Send calendar invites
      });

      console.log('📅 Calendar event created:', response.data.id);

      // Extract the PROPER Google Meet link
      const conferenceData = response.data.conferenceData;
      
      if (!conferenceData || !conferenceData.entryPoints) {
        console.log('⚠️  No conference data returned. Response:', JSON.stringify(response.data, null, 2));
        throw new Error('Google Meet room was not created. This usually means Google Meet API is not properly enabled or authenticated.');
      }

      // Find the video entry point (Google Meet link)
      const videoEntry = conferenceData.entryPoints.find(
        entry => entry.entryPointType === 'video'
      );

      if (!videoEntry) {
        throw new Error('No video entry point found in conference data');
      }

      const meetLink = videoEntry.uri;
      const meetingCode = meetLink.match(/meet\.google\.com\/([a-z-]+)/)?.[1];

      console.log('🎉 SUCCESS! PROPER Google Meet room created:');
      console.log('🎯 Meet Link:', meetLink);
      console.log('🔢 Meeting Code:', meetingCode);
      console.log('📅 Calendar Link:', response.data.htmlLink);

      return {
        success: true,
        meetLink: meetLink,
        meetingCode: meetingCode,
        conferenceId: conferenceData.conferenceId,
        eventId: response.data.id,
        calendarLink: response.data.htmlLink,
        instructions: `Join your therapy session: ${meetLink}`,
        type: 'proper-google-meet',
        persistent: true,
        calendarInviteSent: true,
        attendees: response.data.attendees || []
      };

    } catch (error) {
      console.error('❌ Failed to create proper Google Meet room:', error.message);
      
      // Provide specific error messages
      if (error.message.includes('insufficient')) {
        throw new Error('Insufficient permissions. Please grant Calendar access in OAuth flow.');
      }
      
      if (error.message.includes('quota')) {
        throw new Error('Google Calendar API quota exceeded. Please try again later.');
      }
      
      if (error.message.includes('Invalid conference type')) {
        throw new Error('Google Meet is not enabled for this account. Please enable Google Meet or use Google Workspace.');
      }
      
      throw new Error(`Failed to create Google Meet room: ${error.message}`);
    }
  }

  /**
   * Test if proper Google Meet creation is working
   */
  async testProperMeetCreation() {
    const testAppointment = {
      patientName: 'Test Patient',
      patientEmail: 'patient@test.com',
      doctorName: 'Test Doctor', 
      doctorEmail: 'doctor@test.com',
      startDateTime: new Date(Date.now() + 300000).toISOString(), // 5 min from now
      endDateTime: new Date(Date.now() + 660000).toISOString()    // 11 min from now
    };

    try {
      const result = await this.createProperMeetRoom(testAppointment);
      console.log('✅ Test successful! Proper Google Meet creation is working.');
      return result;
    } catch (error) {
      console.error('❌ Test failed:', error.message);
      throw error;
    }
  }
}

module.exports = { ProperGoogleMeet };

