
import { NextResponse } from 'next/server';
import { google } from 'googleapis';
import { prisma } from '@/lib/db';

const oauth2Client = new google.auth.OAuth2(
  process.env.GOOGLE_CLIENT_ID,
  process.env.GOOGLE_CLIENT_SECRET,
  `${process.env.NEXTAUTH_URL}/api/calendar/oauth/google/callback`
);

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

    // Exchange code for tokens
    const { tokens } = await oauth2Client.getToken(code);
    oauth2Client.setCredentials(tokens);

    // Calculate token expiry
    const expiryDate = tokens.expiry_date
      ? new Date(tokens.expiry_date)
      : new Date(Date.now() + 3600 * 1000); // Default 1 hour

    // Save or update calendar sync configuration
    await prisma.calendarSync.upsert({
      where: { userId: state },
      update: {
        provider: 'GOOGLE',
        isEnabled: true,
        accessToken: tokens.access_token || '',
        refreshToken: tokens.refresh_token || undefined,
        tokenExpiry: expiryDate,
        lastSyncedAt: new Date(),
      },
      create: {
        userId: state,
        provider: 'GOOGLE',
        isEnabled: true,
        accessToken: tokens.access_token || '',
        refreshToken: tokens.refresh_token || '',
        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=google_connected`
    );
  } catch (error) {
    console.error('Error in Google OAuth callback:', error);
    return NextResponse.redirect(
      `${process.env.NEXTAUTH_URL}/calendar?error=oauth_failed`
    );
  }
}
