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

// PATCH - Update all tasks in a recurring series
export async function PATCH(request: NextRequest) {
    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 });
    }

    try {
        const body = await request.json();
        const {
            // Identify the series by the representative task's current values
            oldTitle,
            oldRecurrenceInterval,
            oldRecurrenceUnit,
            oldRecurrenceTime,
            // New values to apply
            newTitle,
            newRecurrenceInterval,
            newRecurrenceUnit,
            newRecurrenceTime,
            newRecurrenceEndDate,
            newRecurrenceDays,
        } = body;

        if (!oldTitle) {
            return NextResponse.json({ error: 'oldTitle is required to identify the series' }, { status: 400 });
        }

        // Find all tasks in this recurring series (matching signature)
        const seriesTasks = await prisma.task.findMany({
            where: {
                userId: user.id,
                isRecurring: true,
                title: oldTitle,
                recurrenceInterval: oldRecurrenceInterval || 1,
                recurrenceUnit: oldRecurrenceUnit || 'weeks',
                ...(oldRecurrenceTime ? { recurrenceTime: oldRecurrenceTime } : {}),
            },
        });

        if (seriesTasks.length === 0) {
            return NextResponse.json({ error: 'No recurring tasks found matching this series' }, { status: 404 });
        }

        // Build update data — only include fields that were provided
        const updateData: any = {};
        if (newTitle !== undefined) updateData.title = newTitle;
        if (newRecurrenceInterval !== undefined) updateData.recurrenceInterval = parseInt(newRecurrenceInterval) || 1;
        if (newRecurrenceUnit !== undefined) updateData.recurrenceUnit = newRecurrenceUnit;
        if (newRecurrenceTime !== undefined) updateData.recurrenceTime = newRecurrenceTime || null;
        if (newRecurrenceEndDate !== undefined) updateData.recurrenceEndDate = newRecurrenceEndDate ? new Date(newRecurrenceEndDate) : null;
        if (newRecurrenceDays !== undefined) updateData.recurrenceDays = newRecurrenceDays;

        if (Object.keys(updateData).length === 0) {
            return NextResponse.json({ error: 'No update fields provided' }, { status: 400 });
        }

        // Update all tasks in the series
        const taskIds = seriesTasks.map(t => t.id);
        await prisma.task.updateMany({
            where: { id: { in: taskIds } },
            data: updateData,
        });

        return NextResponse.json({
            success: true,
            updatedCount: taskIds.length,
        });
    } catch (error) {
        console.error('Error updating recurring series:', error);
        return NextResponse.json({ error: 'Failed to update recurring series' }, { status: 500 });
    }
}
