import { NextResponse } from 'next/server';
import { query } from '@/lib/db';
import type { WorkCompleted } from '@/lib/types';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get('projectId');
    const limit = searchParams.get('limit') || '20';

    const workItems = await query<WorkCompleted>(
      `SELECT 
        wc.*,
        s.session_id,
        s.primary_ai_model,
        s.duration_minutes
      FROM work_completed wc
      LEFT JOIN sessions s ON wc.session_id = s.id
      WHERE wc.project_id = $1
      ORDER BY wc.completed_at DESC
      LIMIT $2`,
      [projectId || 1, limit]
    );

    // Parse JSON fields
    const parsedWork = workItems.map(item => ({
      ...item,
      files_modified: typeof item.files_modified === 'string'
        ? JSON.parse(item.files_modified as any)
        : item.files_modified,
    }));

    return NextResponse.json(parsedWork);
  } catch (error) {
    console.error('Error fetching work completed:', error);
    return NextResponse.json(
      { error: 'Failed to fetch work completed' },
      { status: 500 }
    );
  }
}

