
import { NextResponse } from 'next/server';
import { ConfidentialClientApplication } from '@azure/msal-node';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

const redirectUri = `${process.env.NEXTAUTH_URL}/api/calendar/oauth/microsoft/callback`;

// Create MSAL client only when needed to avoid build-time errors
function createMsalClient() {
  const clientId = process.env.MICROSOFT_CLIENT_ID;
  const clientSecret = process.env.MICROSOFT_CLIENT_SECRET;

  if (!clientId || !clientSecret) {
    throw new Error('Microsoft OAuth credentials not configured. Please set MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET environment variables.');
  }

  const msalConfig = {
    auth: {
      clientId,
      authority: 'https://login.microsoftonline.com/common',
      clientSecret,
    },
  };

  return new ConfidentialClientApplication(msalConfig);
}

// Initiate OAuth flow
export async function GET() {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const pca = createMsalClient();

    const authCodeUrlParameters = {
      scopes: ['Calendars.ReadWrite', 'offline_access'],
      redirectUri: redirectUri,
      state: session.user.id,
    };

    const authUrl = await pca.getAuthCodeUrl(authCodeUrlParameters);

    return NextResponse.json({ authUrl });
  } catch (error) {
    console.error('Error initiating Microsoft OAuth:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to initiate OAuth' },
      { status: 500 }
    );
  }
}
