export type AccountResponse = { status: number; chunks: AsyncIterable<Uint8Array> };
export type AccountRequest = { path: string; method: string; body?: unknown; auth: string };
export type AccountCapture = { raw: Uint8Array; status: number | null; outcome: string; complete: boolean };
export type AccountHTTPPorts = {
  request(input: AccountRequest): Promise<AccountResponse>;
  capture(input: AccountCapture): Promise<void>;
};
export function createAccountHTTP(ports: AccountHTTPPorts, maxBytes: number) {
  if (!ports?.request || !ports?.capture || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 1_048_576) throw new Error('Invalid account HTTP ports or bound');
  return async (input: AccountRequest) => {
    const response = await ports.request(input);
    const chunks: Uint8Array[] = [];
    let size = 0;
    for await (const chunk of response.chunks) {
      size += chunk.length;
      if (size > maxBytes) throw new Error('account response cap');
      chunks.push(chunk);
    }
    const raw = new Uint8Array(size);
    let offset = 0;
    for (const chunk of chunks) { raw.set(chunk, offset); offset += chunk.length; }
    const body = size ? JSON.parse(new TextDecoder().decode(raw)) : null;
    await ports.capture({ raw, status: response.status, outcome: 'complete', complete: true });
    return { status: response.status, body };
  };
}
