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

export async function POST(
  _request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const registration = getA2PRegistration(params.id);

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

    // Only allow retry on failed or manual_review statuses
    const retryableStatuses = ['brand_failed', 'campaign_failed', 'manual_review'];
    if (!retryableStatuses.includes(registration.status)) {
      return NextResponse.json(
        { error: `Cannot retry registration with status: ${registration.status}` },
        { status: 400 }
      );
    }

    if (registration.attempt_count >= registration.max_attempts) {
      return NextResponse.json(
        { error: 'Maximum retry attempts reached' },
        { status: 400 }
      );
    }

    // Reset status to pending for re-processing
    updateA2PStatus(params.id, 'pending');

    return NextResponse.json({
      id: params.id,
      status: 'pending',
      message: 'Registration queued for retry. Submission will begin shortly.',
      attemptCount: registration.attempt_count + 1,
      maxAttempts: registration.max_attempts,
    });
  } catch (error) {
    console.error(`POST /api/a2p/${params.id}/retry error:`, error);
    return NextResponse.json(
      { error: 'Failed to retry registration' },
      { status: 500 }
    );
  }
}
