
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/db';
import ical from 'ical-generator';

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

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

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

    // Get events for the next 3 months
    const startDate = new Date();
    const endDate = new Date();
    endDate.setMonth(endDate.getMonth() + 3);

    const events = await prisma.calendarEvent.findMany({
      where: {
        userId: user.id,
        isDeleted: false,
        startTime: {
          gte: startDate,
          lte: endDate
        }
      },
      orderBy: { startTime: 'asc' }
    });

    // Create ICS calendar
    const calendar = ical({ name: 'Quote2Contract Calendar' });

    events.forEach((event: any) => {
      calendar.createEvent({
        id: event.id,
        start: event.startTime,
        end: event.endTime,
        summary: event.title,
        description: event.description || '',
        location: event.location || '',
        allDay: event.allDay,
        organizer: {
          name: user.name || 'Quote2Contract',
          email: user.email
        }
      });
    });

    const icsContent = calendar.toString();

    return new NextResponse(icsContent, {
      headers: {
        'Content-Type': 'text/calendar; charset=utf-8',
        'Content-Disposition': 'attachment; filename="quote2contract-calendar.ics"'
      }
    });
  } catch (error) {
    console.error('Error exporting calendar:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
