import { NextResponse } from 'next/server';
import connectToDatabase from '@/lib/mongodb';
import TaskCompletion from '@/models/TaskCompletion';

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

    const query: Record<string, unknown> = {};
    if (date) {
      query.date = date;
    } else if (startDate && endDate) {
      query.date = { $gte: startDate, $lte: endDate };
    }

    const completions = await TaskCompletion.find(query).sort({ date: 1, scheduledStart: 1 });
    return NextResponse.json(completions);
  } catch (error: Error | unknown) {
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Failed to process request' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    await connectToDatabase();
    const data = await request.json();

    if (Array.isArray(data)) {
      // Handle bulk update (from daily check-in modal)
      const operations = data.map((item) => ({
        updateOne: {
          filter: { date: item.date, scheduledStart: item.scheduledStart, activityName: item.activityName },
          update: { $set: item },
          upsert: true,
        },
      }));

      await TaskCompletion.bulkWrite(operations);
      return NextResponse.json({ success: true, count: data.length });
    } else {
      // Handle single update
      const updated = await TaskCompletion.findOneAndUpdate(
        { date: data.date, scheduledStart: data.scheduledStart, activityName: data.activityName },
        { $set: data },
        { new: true, upsert: true }
      );
      return NextResponse.json(updated);
    }
  } catch (error: Error | unknown) {
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Failed to process request' }, { status: 500 });
  }
}

export async function DELETE(_request: Request) {
  try {
    await connectToDatabase();
    await TaskCompletion.deleteMany({});
    return NextResponse.json({ success: true, message: "History cleared." });
  } catch (error: Error | unknown) {
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Failed to process request' }, { status: 500 });
  }
}
