export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const orderId = searchParams.get('orderId');
    const executionId = searchParams.get('executionId');

    if (!orderId && !executionId) {
      return NextResponse.json({ error: 'Order ID or Execution ID required' }, { status: 400 });
    }

    const execution = await prisma.orderToCashExecution.findFirst({
      where: orderId ? { orderId } : { id: executionId! },
    });

    if (!execution) {
      return NextResponse.json({ error: 'Execution not found' }, { status: 404 });
    }

    // Get associated agent actions
    const actions = await prisma.agentAction.findMany({
      where: { executionId: execution.id },
      orderBy: { createdAt: 'asc' },
    });

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