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

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

export async function GET(request: NextRequest) {
  try {
    const token = request.headers.get('Authorization');

    console.log('👤 [Proxy] Get profile request:', {
      hasToken: !!token,
      timestamp: new Date().toISOString(),
    });

    if (!token) {
      return NextResponse.json(
        { message: '인증 토큰이 필요합니다.' },
        { status: 401 }
      );
    }

    const response = await fetch(`${GATEWAY_HOST}/api/v1/users/profile`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: token,
      },
    });

    const data = await response.json();

    console.log('📥 [Proxy] Get profile response:', {
      status: response.status,
      success: response.ok,
    });

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

    return NextResponse.json(data);
  } catch (error) {
    console.error('❌ [Proxy] Get profile error:', error);
    return NextResponse.json(
      { message: '프로필 조회 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const token = request.headers.get('Authorization');
    const body = await request.json();

    console.log('✏️ [Proxy] Update profile request:', {
      hasToken: !!token,
      timestamp: new Date().toISOString(),
    });

    if (!token) {
      return NextResponse.json(
        { message: '인증 토큰이 필요합니다.' },
        { status: 401 }
      );
    }

    const response = await fetch(`${GATEWAY_HOST}/api/v1/users/profile`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: token,
      },
      body: JSON.stringify(body),
    });

    const data = await response.json();

    console.log('📥 [Proxy] Update profile response:', {
      status: response.status,
      success: response.ok,
    });

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

    return NextResponse.json(data);
  } catch (error) {
    console.error('❌ [Proxy] Update profile error:', error);
    return NextResponse.json(
      { message: '프로필 수정 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}
