import { NextResponse } from 'next/server';

import { itReadApiBaseUrl, itReadApiKey, requireItOpsSession } from '@/app/api/it/_auth';

export async function GET() {
  const session = await requireItOpsSession();
  if (!session) {
    return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
  }

  const base = itReadApiBaseUrl();
  if (!base) {
    return NextResponse.json(
      { message: 'IT_READ_API_URL is not configured on the portal server' },
      { status: 503 },
    );
  }

  const url = `${base.replace(/\/$/, '')}/v1/summary`;
  const headers: Record<string, string> = { Accept: 'application/json' };
  const key = itReadApiKey();
  if (key) {
    headers['X-API-Key'] = key;
  }

  const res = await fetch(url, { headers, cache: 'no-store' });
  const text = await res.text();
  if (!res.ok) {
    return NextResponse.json(
      { message: 'Upstream summary fetch failed', status: res.status, body: text.slice(0, 2000) },
      { status: 502 },
    );
  }
  try {
    const data = JSON.parse(text) as unknown;
    return NextResponse.json(data);
  } catch {
    return NextResponse.json({ message: 'Invalid JSON from IT read API' }, { status: 502 });
  }
}
