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

const PARTICIPATION_API_BASE_URL = 'http://kt-event-marketing-api.20.214.196.128.nip.io';

export async function GET(
  request: NextRequest,
  { params }: { params: { eventId: string } }
) {
  try {
    const { eventId } = params;
    const { searchParams } = new URL(request.url);

    // Extract query parameters
    const page = searchParams.get('page') || '0';
    const size = searchParams.get('size') || '20';
    const sort = searchParams.getAll('sort');

    // Build query string
    const queryParams = new URLSearchParams();
    queryParams.append('page', page);
    queryParams.append('size', size);
    sort.forEach(s => queryParams.append('sort', s));

    const url = `${PARTICIPATION_API_BASE_URL}/api/v1/participations/api/v1/events/${eventId}/winners?${queryParams.toString()}`;

    console.log('🔄 Proxying winners list request to Participation API:', {
      url,
      eventId,
      params: { page, size, sort },
    });

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('❌ Participation API error:', response.status, errorText);
      return NextResponse.json(
        { error: 'Failed to get winners', details: errorText },
        { status: response.status }
      );
    }

    const data = await response.json();
    console.log('✅ Winners retrieved:', data);

    return NextResponse.json(data);
  } catch (error) {
    console.error('❌ Proxy error:', error);
    return NextResponse.json(
      { error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    );
  }
}
