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

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

export async function GET(
  request: NextRequest,
  { params }: { params: { userId: string } }
) {
  try {
    const { userId } = params;
    const token = request.headers.get('Authorization');
    const { searchParams } = new URL(request.url);

    console.log('📊 [Analytics Proxy] Get user channels request:', {
      userId,
      hasToken: !!token,
      params: Object.fromEntries(searchParams),
    });

    const headers: HeadersInit = {
      'Content-Type': 'application/json',
    };

    if (token) {
      headers['Authorization'] = token;
    }

    const queryString = searchParams.toString();
    const url = `${ANALYTICS_HOST}/api/v1/analytics/users/${userId}/analytics/channels${queryString ? `?${queryString}` : ''}`;

    console.log('🔗 [Analytics Proxy] Calling backend URL:', url);

    const response = await fetch(url, {
      method: 'GET',
      headers,
    });

    const data = await response.json();

    console.log('✅ [Analytics Proxy] User channels response:', {
      status: response.status,
      success: response.ok,
      dataSource: data?.data?.dataSource,
    });

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status });
    }

    return NextResponse.json(data);
  } catch (error) {
    console.error('❌ [Analytics Proxy] User channels error:', error);
    return NextResponse.json(
      { message: 'Channels 데이터 조회 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}
