import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/lib/auth";
import { getAuthUrl } from '@/lib/outlook-calendar';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
    try {
        const session = await getServerSession(authOptions);

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

        const authUrl = getAuthUrl();
        return NextResponse.redirect(authUrl);
    } catch (error) {
        console.error('Error initiating Outlook OAuth:', error);
        return NextResponse.json(
            { error: 'Failed to initiate Outlook Calendar connection. Check server logs.' },
            { status: 500 }
        );
    }
}
