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 ||
  'https://api.sankofa.nexus';

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

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

  const url = new URL(request.url);
  const environment = url.searchParams.get('environment') || 'sandbox';
  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/openpayd/status?environment=${encodeURIComponent(environment)}`, {
    headers,
    cache: 'no-store',
  });
  const data = await res.json().catch(() => ({}));
  return NextResponse.json(data, { status: res.status });
}
