import { UserManager } from "oidc-client-ts";
import { AuthProviderProps } from "react-oidc-context";

const ORIGIN_URI = globalThis?.window?.location.origin;
const REDIRECT_URI = `${ORIGIN_URI}/auth/callback`;

const userConfig: AuthProviderProps = {
  authority: process.env.NEXT_PUBLIC_AUTHORITY!,
  client_id: process.env.NEXT_PUBLIC_CLIENT_ID!,
  redirect_uri: REDIRECT_URI,
  response_type: "code",
  //includeIdTokenInSilentRenew: true,
  automaticSilentRenew: true,
  scope: "openid profile email offline_access", //TODO: Iets met scopes.
  //accessTokenExpiringNotificationTimeInSeconds: 1 * 60,
  loadUserInfo: true,
  post_logout_redirect_uri: ORIGIN_URI,
  response_mode: "query",
  revokeTokensOnSignout: true,
};

export const userManager = new UserManager(userConfig);

// Some handling of token expiration.
// Hopefully this means login timeout issues are prevented somewhat.
userManager.events.addAccessTokenExpiring(() => {
  console.log("Access token expiring");
  //userManager.signinRedirect(); //TODO: uitzoeken bij welke callback dit trecht komt
});

userManager.events.addAccessTokenExpired(() => {
  console.log("Access token expired");
  //userManager.signinRedirect();
});

export const oidcConfig = { ...userConfig, userManager };
