// src/lib/b2binpay.ts
import "server-only";

const BASE = process.env.B2BINPAY_BASE_URL!;
const CLIENT_ID = process.env.B2BINPAY_CLIENT_ID!;
const CLIENT_SECRET = process.env.B2BINPAY_CLIENT_SECRET!;

type TokenResponse = { data: { attributes: { access: string; expires_in: number; token_type: "Bearer" } } };

export async function getB2binpayToken(): Promise<string> {
  const res = await fetch(`${BASE}/token/`, {
    method: "POST",
    headers: { "Content-Type": "application/vnd.api+json" },
    body: JSON.stringify({
      data: {
        type: "auth-token",
        attributes: { client_id: CLIENT_ID, client_secret: CLIENT_SECRET },
      },
    }),
    cache: "no-store",
  });

  if (!res.ok) throw new Error(`Token error: ${res.status} ${await res.text()}`);
  const json = (await res.json()) as TokenResponse;
  return json.data.attributes.access;
}

export async function b2bFetch(path: string, token: string, init?: RequestInit) {
  const res = await fetch(`${BASE}${path}`, {
    ...init,
    headers: {
      ...(init?.headers || {}),
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/vnd.api+json",
    },
    cache: "no-store",
  });

  if (!res.ok) throw new Error(`B2BINPAY error: ${res.status} ${await res.text()}`);
  return res.json();
}
