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', 'synology'].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: { in: ['google-calendar', 'google'] } },
                orderBy: { provider: 'asc' } // 'google-calendar' sorts before '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 }))
            });
        }

        if (provider === 'synology') {
            const connection = await prisma.calendarConnection.findFirst({
                where: { userId: user.id, provider: 'synology' }
            });

            if (!connection || !connection.accessToken || !connection.refreshToken) {
                return NextResponse.json({ error: 'Synology account not connected' }, { status: 400 });
            }

            const [username, password] = connection.accessToken.split(':');
            const serverUrl = connection.refreshToken;
            
            // Re-export dynamically to avoid circular dependencies in route
            const { fetchSynologyReminderLists } = await import('@/lib/synology-tasks');
            const lists = await fetchSynologyReminderLists(serverUrl, username, password);

            return NextResponse.json({
                lists: lists.map(l => ({ id: l.id, title: l.title }))
            });
        }

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