
import { NextResponse } from 'next/server';
import { ConfidentialClientApplication } from '@azure/msal-node';
import { prisma } from '@/lib/db';

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');
  }

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

  return new ConfidentialClientApplication(msalConfig);
}

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const code = searchParams.get('code');
    const state = searchParams.get('state'); // userId
    const error = searchParams.get('error');

    if (error) {
      return NextResponse.redirect(
        `${process.env.NEXTAUTH_URL}/calendar?error=oauth_denied`
      );
    }

    if (!code || !state) {
      return NextResponse.redirect(
        `${process.env.NEXTAUTH_URL}/calendar?error=invalid_request`
      );
    }

    const pca = createMsalClient();

    // Exchange code for tokens
    const tokenRequest = {
      code: code,
      scopes: ['Calendars.ReadWrite', 'offline_access'],
      redirectUri: redirectUri,
    };

    const response = await pca.acquireTokenByCode(tokenRequest);

    if (!response) {
      throw new Error('Failed to acquire token');
    }

    // Calculate token expiry
    const expiryDate = response.expiresOn || new Date(Date.now() + 3600 * 1000);

    // Note: Microsoft MSAL manages refresh tokens internally via token cache
    // We store the access token only
    await prisma.calendarSync.upsert({
      where: { userId: state },
      update: {
        provider: 'MICROSOFT',
        isEnabled: true,
        accessToken: response.accessToken,
        refreshToken: '', // Microsoft MSAL handles refresh internally
        tokenExpiry: expiryDate,
        lastSyncedAt: new Date(),
      },
      create: {
        userId: state,
        provider: 'MICROSOFT',
        isEnabled: true,
        accessToken: response.accessToken,
        refreshToken: '', // Microsoft MSAL handles refresh internally
        tokenExpiry: expiryDate,
        syncDirection: 'TWO_WAY',
        autoSync: true,
        syncFrequency: 15, // 15 minutes
      },
    });

    // Redirect back to calendar page with success message
    return NextResponse.redirect(
      `${process.env.NEXTAUTH_URL}/calendar?success=microsoft_connected`
    );
  } catch (error) {
    console.error('Error in Microsoft OAuth callback:', error);
    return NextResponse.redirect(
      `${process.env.NEXTAUTH_URL}/calendar?error=oauth_failed`
    );
  }
}
