import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/lib/auth";
import { google } from 'googleapis';

export const dynamic = 'force-dynamic';

// Initiate Google Calendar OAuth flow
export async function GET(request: NextRequest) {
    try {
        const session = await getServerSession(authOptions);

        const userId = (session?.user as any)?.id;
        if (!userId) {
            const baseUrl = process.env.NEXTAUTH_URL || request.url;
            return NextResponse.redirect(new URL('/auth/login', baseUrl));
        }

        const clientId = process.env.GOOGLE_CLIENT_ID;
        const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
        const redirectUri = process.env.GOOGLE_REDIRECT_URI || `${process.env.NEXTAUTH_URL}/api/calendar/google/oauth`;

        if (!clientId || !clientSecret) {
            return NextResponse.json(
                { error: 'Google OAuth not configured. Please set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.' },
                { status: 500 }
            );
        }

        const oauth2Client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);

        console.log('--- Google OAuth Debug ---');
        console.log('Redirect URI:', redirectUri);
        console.log('Client ID starts with:', clientId?.substring(0, 10));
        console.log('--------------------------');

        // Generate the authorization URL
        const authUrl = oauth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: [
                'https://www.googleapis.com/auth/calendar',
                'https://www.googleapis.com/auth/calendar.events',
                'https://www.googleapis.com/auth/tasks',
            ],
            prompt: 'consent',
            state: userId, // Pass user CUID to identify in callback (not email)
        });

        // Redirect the user to Google's consent screen
        return NextResponse.redirect(authUrl);
    } catch (error) {
        console.error('Error initiating Google OAuth:', error);
        return NextResponse.json(
            { error: 'Failed to initiate Google Calendar connection' },
            { status: 500 }
        );
    }
}
