import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from "@/lib/auth"; import { PrismaClient } from '@prisma/client'; import { createGoogleClient, fetchGoogleTaskLists } from '@/lib/google-tasks'; import { fetchMsTodoLists } from '@/lib/microsoft-todo'; import { getOutlookAccessToken } from '@/lib/outlook-token'; export const dynamic = 'force-dynamic'; const prisma = new PrismaClient(); export async function GET(req: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { searchParams } = new URL(req.url); const provider = searchParams.get('provider'); if (!provider || !['google', 'outlook'].includes(provider)) { return NextResponse.json({ error: 'Invalid provider' }, { status: 400 }); } const user = await prisma.user.findUnique({ where: { email: session.user.email } }); if (!user) { return NextResponse.json({ error: 'User not found' }, { status: 404 }); } if (provider === 'google') { const account = await prisma.account.findFirst({ where: { userId: user.id, provider: 'google' } }); if (!account || !account.access_token) { return NextResponse.json({ error: 'Google account not connected' }, { status: 400 }); } const client = createGoogleClient(account.access_token, account.refresh_token || undefined); const lists = await fetchGoogleTaskLists(client); return NextResponse.json({ lists: lists.map(l => ({ id: l.id, title: l.title })) }); } if (provider === 'outlook') { const accessToken = await getOutlookAccessToken(user.id); if (!accessToken) { return NextResponse.json({ error: 'Outlook account not connected' }, { status: 400 }); } const lists = await fetchMsTodoLists(accessToken); return NextResponse.json({ lists: lists.map(l => ({ id: l.id, title: l.displayName })) }); } return NextResponse.json({ error: 'Invalid provider' }, { status: 400 }); } catch (error: unknown) { console.error('Fetch lists error:', error); const message = error instanceof Error ? error.message : 'Failed to fetch lists'; return NextResponse.json({ error: message }, { status: 500 }); } }