import { NextResponse } from 'next/server';
import connectToDatabase from '@/lib/mongodb';
import TaskCompletion from '@/models/TaskCompletion';
import { validateRequest } from '@/lib/auth';
import { format, subDays } from 'date-fns';

export async function GET(request: Request) {
  try {
    const { valid, error } = validateRequest(request);
    if (!valid) {
      return NextResponse.json({ success: false, error }, { status: 401 });
    }

    await connectToDatabase();

    // Look at last 60 days to find the streak
    const today = format(new Date(), 'yyyy-MM-dd');
    const sixtyDaysAgo = format(subDays(new Date(), 60), 'yyyy-MM-dd');

    const completions = await TaskCompletion.find({
      date: { $gte: sixtyDaysAgo, $lte: today },
      completed: true,
    }).select('date').sort({ date: -1 });

    // Get unique dates that have at least one completed task
    const completedDates = new Set(completions.map((c) => c.date));

    let streak = 0;
    const checkDate = new Date();

    // Walk backwards from today
    for (let i = 0; i <= 60; i++) {
      const dateStr = format(subDays(checkDate, i), 'yyyy-MM-dd');
      if (completedDates.has(dateStr)) {
        streak++;
      } else {
        // Allow today to be incomplete (streak hasn't broken yet)
        if (i === 0) continue;
        break;
      }
    }

    // Build last 14 days history for heatmap
    const history: { date: string; completed: number; total: number; rate: number }[] = [];
    for (let i = 13; i >= 0; i--) {
      const dateStr = format(subDays(new Date(), i), 'yyyy-MM-dd');
      const dayCompletions = await TaskCompletion.find({ date: dateStr });
      const completed = dayCompletions.filter((c) => c.completed === true).length;
      const total = dayCompletions.length;
      history.push({
        date: dateStr,
        completed,
        total,
        rate: total > 0 ? Math.round((completed / total) * 100) : 0,
      });
    }

    return NextResponse.json({
      success: true,
      data: {
        currentStreak: streak,
        todayDate: today,
        history,
      },
    });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to fetch streak data' },
      { status: 500 }
    );
  }
}
