import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/lib/auth";
import { prisma } from '@/lib/prisma';

export async function GET(request: Request) {
    const session = await getServerSession(authOptions);
    const { searchParams } = new URL(request.url);
    const startDate = searchParams.get('startDate');
    const endDate = searchParams.get('endDate');

    if (!session || !session.user?.email) {
        return new NextResponse('Unauthorized', { status: 401 });
    }

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

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

        const where: any = {
            userId: user.id,
            completed: true,
        };

        if (startDate || endDate) {
            where.updatedAt = {};
            if (startDate) where.updatedAt.gte = new Date(startDate);
            if (endDate) {
                const end = new Date(endDate);
                end.setHours(23, 59, 59, 999);
                where.updatedAt.lte = end;
            }
        }

        // Fetch filtered tasks
        const tasks = await prisma.task.findMany({
            where,
            orderBy: {
                updatedAt: 'desc',
            },
        });

        // Generate CSV
        const headers = ['Title', 'Description', 'Completed Date', 'Created Date'];
        const rows = tasks.map((task: any) => [
            task.title,
            task.description || '',
            task.updatedAt.toISOString(),
            task.createdAt.toISOString(),
        ]);

        const csvContent = [
            headers.join(','),
            ...rows.map((row: string[]) => row.map((cell: string) => `"${(cell || '').replace(/"/g, '""')}"`).join(','))
        ].join('\n');

        return new NextResponse(csvContent, {
            headers: {
                'Content-Type': 'text/csv',
                'Content-Disposition': `attachment; filename="completed_tasks_${new Date().toISOString().split('T')[0]}.csv"`,
            },
        });
    } catch (error) {
        console.error('Export error:', error);
        return new NextResponse('Internal Server Error', { status: 500 });
    }
}
