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) {
  const sessionToken = request.cookies.get('session_token')?.value;

  if (!sessionToken) {
    return NextResponse.json({ user: null });
  }

  try {
    const backendRes = await fetch(`${API}/auth/me`, {
      headers: {
        Cookie: `session_token=${sessionToken}`,
      },
    });

    const data = await backendRes.json();

    // Backend returns { id, email, role } when authenticated,
    // or { user: null } when not (AppError 401 → reply.send({ user: null }))
    // Normalize into { user: ... }
    if (!backendRes.ok || !data.id) {
      return NextResponse.json({ user: null });
    }

    return NextResponse.json({ user: data });
  } catch {
    return NextResponse.json({ user: null });
  }
}
