import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { authCookieName } from '../../../lib/auth';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';

function buildUrl(searchParams: URLSearchParams) {
  const query = searchParams.toString();
  return `${API_URL}/conversations${query ? `?${query}` : ''}`;
}

export async function GET(request: Request) {
  const token = (await cookies()).get(authCookieName)?.value;
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const url = new URL(request.url);
  const response = await fetch(buildUrl(url.searchParams), {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    cache: 'no-store',
  });

  const payload = await response.json();
  return NextResponse.json(payload, { status: response.status });
}
