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

export const dynamic = 'force-dynamic';

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.NOTION_CLIENT_ID;
        if (!clientId) {
            return NextResponse.json(
                { error: 'Notion OAuth not configured. Please set NOTION_CLIENT_ID and NOTION_CLIENT_SECRET.' },
                { status: 500 }
            );
        }

        const redirectUri = process.env.NOTION_REDIRECT_URI
            || `${process.env.NEXTAUTH_URL}/api/calendar/notion/callback`;

        const authUrl = new URL('https://api.notion.com/v1/oauth/authorize');
        authUrl.searchParams.set('client_id', clientId);
        authUrl.searchParams.set('response_type', 'code');
        authUrl.searchParams.set('owner', 'user');
        authUrl.searchParams.set('redirect_uri', redirectUri);
        authUrl.searchParams.set('state', userId);

        return NextResponse.redirect(authUrl.toString());
    } catch (error) {
        console.error('Error initiating Notion OAuth:', error);
        return NextResponse.json(
            { error: 'Failed to initiate Notion connection' },
            { status: 500 }
        );
    }
}
