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

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

export async function GET(request: NextRequest) {
  const path = request.nextUrl.pathname.replace('/api/', '');
  const search = request.nextUrl.search;
  const cookie = request.headers.get('cookie') ?? '';
  const terminalId = request.headers.get('x-terminal-id');

  const headers: Record<string, string> = { Cookie: cookie };
  if (terminalId) headers['x-terminal-id'] = terminalId;

  const res = await fetch(`${API}/${path}${search}`, { headers, credentials: 'include' });
  const body = await res.text();
  return new NextResponse(body, { status: res.status, headers: { 'content-type': res.headers.get('content-type') ?? 'application/json' } });
}

export async function POST(request: NextRequest) {
  const path = request.nextUrl.pathname.replace('/api/', '');
  const search = request.nextUrl.search;
  const cookie = request.headers.get('cookie') ?? '';
  const terminalId = request.headers.get('x-terminal-id');
  const body = await request.text();

  const headers: Record<string, string> = { 'Content-Type': 'application/json', Cookie: cookie };
  if (terminalId) headers['x-terminal-id'] = terminalId;

  const res = await fetch(`${API}/${path}${search}`, { method: 'POST', headers, body, credentials: 'include' });
  const resBody = await res.text();
  return new NextResponse(resBody, { status: res.status, headers: { 'content-type': res.headers.get('content-type') ?? 'application/json' } });
}
