import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';

import { authOptions } from '@/lib/auth';

const API_BASE =
  process.env.PHOENIX_API_INTERNAL_URL ||
  process.env.NEXT_PUBLIC_PHOENIX_API_URL ||
  'http://192.168.11.50:8080';

type SessionClaims = {
  accessToken?: string;
  tenantId?: string;
} | null;

export async function GET() {
  const session = (await getServerSession(authOptions)) as SessionClaims;
  if (!session?.accessToken) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const headers: Record<string, string> = {
    Authorization: `Bearer ${session.accessToken}`,
  };
  if (session.tenantId) {
    headers['X-Tenant-Id'] = session.tenantId;
  }

  const res = await fetch(`${API_BASE}/api/v1/marketplace/me/entitlements`, {
    headers,
    cache: 'no-store',
  });
  const data = await res.json().catch(() => ({}));
  return NextResponse.json(data, { status: res.status });
}
