import { NextResponse } from 'next/server';
import { validateCredentials } from '@/lib/apple-calendar';
import { CalendarConnection } from '@/lib/calendar-sync';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/lib/auth";
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function POST(req: Request) {
    try {
        const session = await getServerSession(authOptions);
        if (!session?.user?.email) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const body = await req.json();
        const { email, password } = body;

        if (!email || !password) {
            return NextResponse.json(
                { error: 'Email and password are required' },
                { status: 400 }
            );
        }

        // Validate credentials and get calendars
        const calendars = await validateCredentials(email, password);

        // Find user
        const user = await prisma.user.findUnique({
            where: { email: session.user.email }
        });

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

        // Check if connection already exists and update it, otherwise create new
        // We use the provider 'apple' and the user ID to find existing
        const existingConnection = await prisma.calendarConnection.findFirst({
            where: {
                userId: user.id,
                provider: 'apple'
            }
        });

        let connection;

        if (existingConnection) {
            // Update existing connection
            connection = await prisma.calendarConnection.update({
                where: { id: existingConnection.id },
                data: {
                    accessToken: `${email}:${password}`,
                    calendars: calendars.map(cal => ({
                        id: cal.id,
                        title: cal.title,
                        isPrimary: cal.isPrimary,
                        selected: true // Default to selected
                    })) as any,
                    updatedAt: new Date()
                }
            });
        } else {
            // Create new connection
            connection = await prisma.calendarConnection.create({
                data: {
                    userId: user.id,
                    provider: 'apple',
                    accessToken: `${email}:${password}`,
                    calendars: calendars.map(cal => ({
                        id: cal.id,
                        title: cal.title,
                        isPrimary: cal.isPrimary,
                        selected: true // Default to selected
                    })) as any
                }
            });
        }

        return NextResponse.json({ success: true, connection });
    } catch (error: any) {
        console.error('Error connecting Apple Calendar:', error);
        return NextResponse.json(
            { error: error.message || 'Failed to connect Apple Calendar' },
            { status: 500 }
        );
    }
}
