import { NextResponse } from 'next/server';

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

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

  const base = itReadApiBaseUrl();
  const key = itReadApiKey();
  if (!base) {
    return NextResponse.json(
      { message: 'IT_READ_API_URL is not configured on the portal server' },
      { status: 503 },
    );
  }
  if (!key) {
    return NextResponse.json(
      { message: 'IT_READ_API_KEY is required for refresh (server-side only)' },
      { status: 503 },
    );
  }

  const url = `${base.replace(/\/$/, '')}/v1/inventory/refresh`;
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'X-API-Key': key,
    },
    cache: 'no-store',
  });
  const text = await res.text();
  if (!res.ok) {
    return NextResponse.json(
      { message: 'Upstream refresh failed', status: res.status, body: text.slice(0, 4000) },
      { status: 502 },
    );
  }
  try {
    const data = text ? (JSON.parse(text) as unknown) : {};
    return NextResponse.json(data);
  } catch {
    return NextResponse.json({ message: 'Invalid JSON from IT read API' }, { status: 502 });
  }
}
