<script>
import { ref } from "vue";
import * as msal from "@azure/msal-browser";

const IS_DEV = true;
// Initialize MSAL configuration
const msalConfig = {
  auth: {
    clientId: "2e493b11-1b25-4cc1-82eb-626a582320ab", // Application (client) ID from Azure Portal
    authority: "https://login.microsoftonline.com/common",
    redirectUri: IS_DEV ? "http://localhost:5173/callback/microsoft/token" : "https://web.truckwash.dk/callback/microsoft/token", // Should match the one in Azure Portal
  },
  cache: {
    cacheLocation: "localStorage", // Can be "localStorage" or "sessionStorage"
    storeAuthStateInCookie: true,
  }
};

// Create MSAL instance
const msalInstance = new msal.PublicClientApplication(msalConfig);

// Login request object
const loginRequest = {
  scopes: [
    "User.Read",
    "Calendars.ReadWrite",
    "Calendars.Read",
    "offline_access"  // This is important - it enables refresh tokens
  ] // Add required scopes
};

// Function to get a valid token for calendar operations
const getCalendarToken = async () => {
  try {
    const accounts = msalInstance.getAllAccounts();
    if (accounts.length > 0) {
      const silentRequest = {
        account: accounts[0],
        scopes: loginRequest.scopes,
      };

      return await msalInstance.acquireTokenSilent(silentRequest);
    } else {
      // If no account is found, initiate login
      return await msalInstance.loginPopup(loginRequest);
    }
  } catch (error) {
    if (error instanceof msal.InteractionRequiredAuthError) {
      return await msalInstance.acquireTokenPopup(loginRequest);
    }
    throw error;
  }
};

// Example calendar operations functions
const calendarOperations = {
  async getEvents() {
    const tokenResponse = await getCalendarToken();
    // Use the token to make Graph API calls
    // Example using fetch:
    const response = await fetch('https://graph.microsoft.com/v1.0/me/events', {
      headers: {
        'Authorization': `Bearer ${tokenResponse.accessToken}`
      }
    });
    return response.json();
  },
  async addEvent(eventDetails) {
    const tokenResponse = await getCalendarToken();
    // Use the token to make Graph API calls
    // Example using fetch:
    const response = await fetch('https://graph.microsoft.com/v1.0/me/events', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${tokenResponse.accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(eventDetails)
    });
    return response.json();
  },

  async updateEvent(eventId, updateDetails) {
    const tokenResponse = await getCalendarToken();
    const response = await fetch(`https://graph.microsoft.com/v1.0/me/events/${eventId}`, {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${tokenResponse.accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updateDetails)
    });
    return response.status === 200;
  },

  async deleteEvent(eventId) {
    const tokenResponse = await getCalendarToken();
    const response = await fetch(`https://graph.microsoft.com/v1.0/me/events/${eventId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${tokenResponse.accessToken}`
      }
    });
    return response.status === 204;
  }
};

// Initiate msal instance
const isAuthenticated = ref(false);
const user = ref(null);
const checkAccount = async () => {
  await msalInstance.initialize();
  const accounts = msalInstance.getAllAccounts();
  if (accounts.length > 0) {
    isAuthenticated.value = true;
    user.value = accounts[0];
  } else {
    isAuthenticated.value = false;
  }
};
// Check if the user is authenticated
const checkUserAuthentication = async () => {
  // Initialize MSAL instance
  await msalInstance.initialize();
  try {
    await msalInstance.handleRedirectPromise();
    const accounts = msalInstance.getAllAccounts();
    if (accounts.length > 0) {
      isAuthenticated.value = true;
      user.value = accounts[0];
    } else {
      isAuthenticated.value = false;
    }
  } catch (error) {
    console.error("Error during authentication:", error);
  }
};
// Call the function to check user authentication
checkUserAuthentication();

// Function to handle login
const onClickLogin = async () => {
  try {
    const loginResponse = await msalInstance.loginPopup(loginRequest);
    console.log("Login successful:", loginResponse);
  } catch (error) {
    console.error("Login failed:", error);
  }
};
// Function to handle logout
const onClickLogout = () => {
  msalInstance.logout();
};

// Example usage of calendar operations
const addNewBooking = async () => {
  // Get the dateTime for now, and add 1 hour
  const now = new Date();
  const startTime = new Date(now.getTime() + 1 * 60 * 60 * 1000); // Add 1 hour
  const endTime = new Date(startTime.getTime() + 1 * 60 * 60 * 1000); // Add 1 hour
  try {
    const eventDetails = {
      subject: "New Booking",
      start: {
        dateTime: startTime.toISOString(),
        timeZone: "UTC"
      },
      end: {
        dateTime: endTime.toISOString(),
        timeZone: "UTC"
      }
    };

    const result = await calendarOperations.addEvent(eventDetails);
    console.log('Booking added:', result);
  } catch (error) {
    console.error('Failed to add booking:', error);
  }
};


export {
  onClickLogin,
  onClickLogout,
  calendarOperations,
  addNewBooking,
  checkUserAuthentication,
  isAuthenticated,
  user,
  checkAccount,
  msalInstance,
  loginRequest,
  getCalendarToken,
};


</script>