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

const EVENT_API_HOST =
  process.env.NEXT_PUBLIC_EVENT_HOST || 'http://kt-event-marketing-api.20.214.196.128.nip.io';
const API_VERSION = process.env.NEXT_PUBLIC_API_VERSION || 'v1';

/**
 * Event API Proxy: AI 추천 요청
 * POST /api/events/{eventId}/ai-recommendations
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { eventId: string } }
) {
  try {
    const { eventId } = params;
    const body = await request.json();

    const backendUrl = `${EVENT_API_HOST}/api/${API_VERSION}/events/${eventId}/ai-recommendations`;

    console.log('🤖 Proxying AI recommendation request to:', backendUrl);
    console.log('📦 Request body:', body);

    const backendResponse = await fetch(backendUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: request.headers.get('Authorization') || '',
      },
      body: JSON.stringify(body),
    });

    const data = await backendResponse.json();

    console.log('✅ AI recommendation response:', {
      status: backendResponse.status,
      data: data,
    });

    return NextResponse.json(data, { status: backendResponse.status });
  } catch (error) {
    console.error('❌ AI recommendation POST proxy error:', error);

    return NextResponse.json(
      {
        success: false,
        errorCode: 'PROXY_ERROR',
        message: 'AI 추천 요청 중 오류가 발생했습니다',
        details: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    );
  }
}

/**
 * Event API Proxy: AI 추천 결과 조회
 * GET /api/events/{eventId}/ai-recommendations
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { eventId: string } }
) {
  try {
    const { eventId } = params;

    const backendUrl = `${EVENT_API_HOST}/api/${API_VERSION}/events/${eventId}/ai-recommendations`;

    console.log('🔍 Proxying AI recommendation GET request to:', backendUrl);

    const backendResponse = await fetch(backendUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: request.headers.get('Authorization') || '',
      },
    });

    const data = await backendResponse.json();

    console.log('✅ AI recommendation GET response:', {
      status: backendResponse.status,
      data: data,
    });

    return NextResponse.json(data, { status: backendResponse.status });
  } catch (error) {
    console.error('❌ AI recommendation GET proxy error:', error);

    return NextResponse.json(
      {
        success: false,
        errorCode: 'PROXY_ERROR',
        message: 'AI 추천 결과 조회 중 오류가 발생했습니다',
        details: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    );
  }
}
