import { NextResponse } from 'next/server';

/**
 * GET /api/wren/portfolios
 * Proxy endpoint to fetch portfolios from Wren API
 * This keeps the WREN_API_TOKEN secure on the server
 */
export async function GET() {
  try {
    const apiToken = process.env.WREN_API_TOKEN;

    if (!apiToken) {
      console.error('WREN_API_TOKEN is not configured');
      return NextResponse.json(
        { error: 'Wren API is not configured' },
        { status: 500 }
      );
    }

    const response = await fetch('https://www.wren.co/api/portfolios', {
      headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Wren API error:', response.status, errorText);
      return NextResponse.json(
        { error: 'Failed to fetch portfolios from Wren' },
        { status: response.status }
      );
    }

    const data = await response.json();
    return NextResponse.json(data);
  } catch (error) {
    console.error('Error fetching Wren portfolios:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch portfolios' },
      { status: 500 }
    );
  }
}
