import { MsGraphClient, MsGraphClientConfig } from './msgraph-client';

let msGraphClientInstance: MsGraphClient | null = null;

/**
 * Check if Microsoft Graph credentials are configured
 */
export function isMsgraphConfigured(): boolean {
  return !!(
    process.env.MSGRAPH_CLIENT_ID &&
    process.env.MSGRAPH_CLIENT_SECRET &&
    process.env.MSGRAPH_TENANT_ID
  );
}

/**
 * Get or create Microsoft Graph client singleton
 */
export function getMsgraphClient(): MsGraphClient {
  if (!msGraphClientInstance) {
    const config: MsGraphClientConfig = {
      tenantId: process.env.MSGRAPH_TENANT_ID || '',
      clientId: process.env.MSGRAPH_CLIENT_ID || '',
      clientSecret: process.env.MSGRAPH_CLIENT_SECRET || '',
    };

    if (!config.tenantId || !config.clientId || !config.clientSecret) {
      throw new Error(
        'Microsoft Graph credentials missing. Set MSGRAPH_CLIENT_ID, MSGRAPH_CLIENT_SECRET, and MSGRAPH_TENANT_ID.'
      );
    }

    msGraphClientInstance = new MsGraphClient(config);
    console.log('[MSGRAPH] Client initialized');
  }

  return msGraphClientInstance;
}

export function resetMsgraphClient(): void {
  msGraphClientInstance = null;
}
