/**
 * GET /api/ticket-workflows/:id/executions - List executions for a workflow
 */

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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const { searchParams } = new URL(request.url);
    const limit = Number(searchParams.get('limit')) || 50;
    const offset = Number(searchParams.get('offset')) || 0;

    const result = await postgresClient.query<TicketWorkflowExecution>(
      `SELECT * FROM ticket_workflow_executions
       WHERE workflow_id = $1
       ORDER BY created_at DESC
       LIMIT $2 OFFSET $3`,
      [id, limit, offset]
    );

    const countResult = await postgresClient.query(
      `SELECT COUNT(*) FROM ticket_workflow_executions WHERE workflow_id = $1`,
      [id]
    );

    return NextResponse.json({
      executions: result.rows,
      total: Number(countResult.rows[0].count)
    });
  } catch (error) {
    console.error('[API] Error fetching workflow executions:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch executions' },
      { status: 500 }
    );
  }
}
