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

export async function proxyAuth(
  request: NextRequest,
  method: 'GET' | 'POST' | 'PUT',
  path: string,
) {
  const backendUrl = process.env.BACKEND_URL;
  const appToken = process.env.STORE_APP_TOKEN;
  if (!backendUrl || !appToken) {
    return NextResponse.json({ message: 'Tienda no configurada' }, { status: 500 });
  }

  const headers: Record<string, string> = {
    'x-app-key': appToken,
    'Content-Type': 'application/json',
  };

  // Reenviar Authorization del cliente si existe
  const auth = request.headers.get('authorization');
  if (auth) headers['Authorization'] = auth;

  let body: string | undefined;
  if (method !== 'GET') {
    try { body = JSON.stringify(await request.json()); } catch { body = undefined; }
  }

  try {
    const res = await fetch(`${backendUrl}/api/v1${path}`, {
      method,
      headers,
      body,
      signal: AbortSignal.timeout(10000),
    });
    const data = await res.json().catch(() => ({}));
    return NextResponse.json(data, { status: res.status });
  } catch {
    return NextResponse.json({ message: 'No se pudo conectar con el servidor' }, { status: 502 });
  }
}
