import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/lib/auth";
import { prisma } from '@/lib/prisma';
import { readCachedEvents, isCacheStale, refreshConnectionCache, RefreshableConnection } from '@/lib/calendar-cache';

export async function POST(request: NextRequest) {
    try {
        const session = await getServerSession(authOptions);
        const userId = (session?.user as any)?.id;
        if (!userId) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const body = await request.json();
        const { timeMin, timeMax, connectionId, forceRefresh } = body;

        const timeMinDate = new Date(timeMin ?? Date.now());
        const timeMaxDate = new Date(timeMax ?? Date.now() + 7 * 24 * 60 * 60 * 1000);

        const user = await prisma.user.findUnique({
            where: { id: userId },
            include: { calendarConnections: true },
        });

        if (!user) {
            return NextResponse.json({ error: 'User not found' }, { status: 404 });
        }

        let connections = user.calendarConnections;
        if (connectionId) {
            connections = connections.filter(c => c.id === connectionId);
        }

        if (connections.length === 0) {
            return NextResponse.json({ success: true, events: [], fromCache: true });
        }

        // FAST PATH: read from DB cache
        const cachedEvents = await readCachedEvents(user.id, timeMinDate, timeMaxDate);

        // Check which connections are stale
        const staleChecks = await Promise.all(
            connections.map(async conn => ({
                conn,
                stale: forceRefresh || await isCacheStale(conn.id, timeMinDate),
            }))
        );
        const staleConnections = staleChecks.filter(c => c.stale).map(c => c.conn);

        // Refresh stale connections
        if (staleConnections.length > 0) {
            const doRefresh = () => Promise.allSettled(
                staleConnections.map(conn => {
                    const rc: RefreshableConnection = {
                        dbId: conn.id,
                        userId: user.id,
                        id: conn.id,
                        provider: conn.provider as 'google' | 'apple' | 'outlook' | 'synology',
                        accessToken: conn.accessToken,
                        refreshToken: conn.refreshToken ?? undefined,
                        expiresAt: conn.expiresAt ?? undefined,
                        calendars: conn.calendars as any,
                    };
                    return refreshConnectionCache(rc, timeMinDate, timeMaxDate);
                })
            );

            if (forceRefresh) {
                // BLOCKING: wait for fresh data when user explicitly requests refresh
                await doRefresh();
                const freshEvents = await readCachedEvents(user.id, timeMinDate, timeMaxDate);
                return NextResponse.json({
                    success: true,
                    events: freshEvents,
                    count: freshEvents.length,
                    fromCache: false,
                    staleConnectionCount: 0,
                });
            } else {
                // BACKGROUND: fire-and-forget for automatic refresh
                const refreshWork = doRefresh();
                refreshWork.catch(e => console.error('[CACHE] Background refresh error:', e));
            }
        }

        return NextResponse.json({
            success: true,
            events: cachedEvents,
            count: cachedEvents.length,
            fromCache: true,
            staleConnectionCount: staleConnections.length,
        });
    } catch (error) {
        console.error('[CALENDAR SYNC] Sync request failed:', error);
        return NextResponse.json({
            error: 'Sync failed',
            details: error instanceof Error ? error.message : 'Unknown error'
        }, { status: 500 });
    }
}
