import { NextRequest, NextResponse } from 'next/server';
import postgresClient from '@/lib/services/postgres-client';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200);
    const offset = parseInt(searchParams.get('offset') || '0');
    const status = searchParams.get('status');
    const method = searchParams.get('method');
    const branch = searchParams.get('branch');

    const conditions: string[] = [];
    const params: any[] = [];
    let paramIndex = 1;

    if (status) {
      conditions.push(`status = $${paramIndex++}`);
      params.push(status);
    }
    if (method) {
      conditions.push(`classification_method = $${paramIndex++}`);
      params.push(method);
    }
    if (branch) {
      conditions.push(`branch = $${paramIndex++}`);
      params.push(branch);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    const [executions, countResult] = await Promise.all([
      postgresClient.query(
        `SELECT * FROM workflow_executions ${whereClause} ORDER BY created_at DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`,
        [...params, limit, offset]
      ),
      postgresClient.query(
        `SELECT COUNT(*) as total FROM workflow_executions ${whereClause}`,
        params
      ),
    ]);

    return NextResponse.json({
      data: executions.rows,
      total: parseInt(countResult.rows[0].total),
      limit,
      offset,
    });
  } catch (error) {
    console.error('Failed to fetch executions:', error);
    return NextResponse.json({ error: 'Failed to fetch executions' }, { status: 500 });
  }
}
