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

const API = process.env.NEXT_PUBLIC_API_URL ?? 'http://127.0.0.1:3000';

export async function GET(request: NextRequest) {
  return handle(request);
}

export async function POST(request: NextRequest) {
  return handle(request);
}

export async function PATCH(request: NextRequest) {
  return handle(request);
}

async function handle(request: NextRequest): Promise<NextResponse> {
  const path = request.nextUrl.pathname.replace('/api/', '');
  const url = `${API}/${path}${request.nextUrl.search}`;
  const headers: Record<string, string> = { accept: 'application/json' };
  const cookie = request.headers.get('cookie');
  if (cookie) headers.cookie = cookie;
  const contentType = request.headers.get('content-type');
  if (contentType) headers['content-type'] = contentType;

  const init: RequestInit = { method: request.method, headers };
  if (request.method !== 'GET' && request.method !== 'HEAD') {
    init.body = await request.text();
  }

  try {
    const response = await fetch(url, init);
    const body = await response.json().catch(() => ({}));
    const next = NextResponse.json(body, { status: response.status });
    const setCookie = response.headers.get('set-cookie');
    if (setCookie) next.headers.set('set-cookie', setCookie);
    return next;
  } catch (error) {
    return NextResponse.json(
      { error: { code: 'PROXY_ERROR', message: error instanceof Error ? error.message : 'Club proxy failed' } },
      { status: 502 },
    );
  }
}
