import { NextRequest, NextResponse } from 'next/server';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8001';

/**
 * POST /api/jobs/[jobId]/retry
 *
 * Retries a failed or partial job, optionally applying auto-fix parameters.
 *
 * Query params:
 * - apply_fix: boolean (default: false) - Whether to apply auto-fix parameters
 *   based on crash analysis (e.g., reduced batch size for memory issues)
 *
 * Returns the new job ID for tracking the retry attempt.
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ jobId: string }> }
) {
  try {
    const { jobId } = await params;
    const searchParams = request.nextUrl.searchParams;
    const applyFix = searchParams.get('apply_fix') === 'true';

    const response = await fetch(
      `${API_BASE_URL}/jobs/${jobId}/retry?apply_fix=${applyFix}`,
      {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      }
    );

    const data = await response.json();

    if (!response.ok) {
      return NextResponse.json(
        { error: data.detail || 'Failed to retry job' },
        { status: response.status }
      );
    }

    return NextResponse.json(data);
  } catch (error) {
    console.error('Retry job API error:', error);
    return NextResponse.json(
      { error: 'Failed to retry job' },
      { status: 500 }
    );
  }
}
