import { NextResponse } from 'next/server';
import { authSession } from "@/lib/auth/session-server";
import { query } from '@/lib/db-postgres';

export async function GET(request: Request) {
  try {
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json([], { status: 200 });
    }

    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get('projectId');
    const limit = parseInt(searchParams.get('limit') || '50');

    let rows: any[];
    if (projectId) {
      rows = await query<any>(
        `SELECT s.id, s.data, s.created_at
         FROM fs_sessions s
         JOIN fs_users u ON u.id = s.user_id
         WHERE u.data->>'email' = $1 AND s.data->>'projectId' = $2
         ORDER BY s.created_at DESC LIMIT $3`,
        [session.user.email, projectId, limit]
      );
    } else {
      rows = await query<any>(
        `SELECT s.id, s.data, s.created_at
         FROM fs_sessions s
         JOIN fs_users u ON u.id = s.user_id
         WHERE u.data->>'email' = $1
         ORDER BY s.created_at DESC LIMIT $2`,
        [session.user.email, limit]
      );
    }

    const sessions = rows.map((row: any) => {
      const d = row.data ?? {};
      return {
        id: row.id,
        session_id: row.id,
        projectId: d.projectId,
        userId: d.userId,
        workspacePath: d.workspacePath,
        workspaceName: d.workspaceName,
        startTime: d.startTime,
        endTime: d.endTime,
        duration: d.duration,
        duration_minutes: d.duration ? Math.round(d.duration / 60) : 0,
        tokensUsed: d.tokensUsed || 0,
        total_tokens: d.tokensUsed || 0,
        cost: d.cost || 0,
        estimated_cost_usd: d.cost || 0,
        model: d.model || 'unknown',
        primary_ai_model: d.model || 'unknown',
        filesModified: d.filesModified || [],
        summary: d.conversationSummary || null,
        message_count: d.messageCount || 0,
        ide_name: 'Cursor',
        github_branch: d.githubBranch || null,
        conversation: d.conversation || [],
        file_changes: d.fileChanges || [],
        createdAt: row.created_at,
        last_updated: d.updatedAt || row.created_at,
      };
    });

    console.log(`[API] Found ${sessions.length} sessions from PostgreSQL`);
    return NextResponse.json(sessions);
  } catch (error) {
    console.error('[API] Error fetching sessions:', error);
    return NextResponse.json([]);
  }
}
