// Media-upload fixture for the integration tier.
//
// Pixelfed is image-first: a top-level status is rejected with
// `403 {"error":"Empty statuses are not allowed"}` unless it carries
// `media_ids`, an `in_reply_to_id`, or a quote (see the server's
// ApiV1Controller status-create guard). So any Pixelfed compose round-trip
// needs a real attachment. This helper uploads a tiny PNG and returns the
// resulting media id for the caller to attach.
//
// Why a raw `fetch` instead of the production `ApiContext.postFormIdempotent`:
// the production form helpers hard-set `Content-Type: multipart/form-data`
// with no boundary. React Native's fetch silently rewrites that header with
// the correct boundary when the body is a FormData; Node's undici fetch does
// not — it forwards the bare header verbatim and the server can't split the
// parts. In this Node test tier we therefore build the multipart ourselves
// (omit Content-Type so undici fills in the boundary). Media upload is a
// fixture here, not the unit under test; the status round-trip that follows
// runs through the production client, where the wire shape matches prod.

import type { RigAccount } from '../../_helpers/loadTestRig'

// A 16x16 opaque PNG. Small enough to keep the upload fast, large enough that
// Pixelfed's image pipeline accepts and processes it without complaint.
const TINY_PNG_BASE64 =
  'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAFklEQVR42mP8z8BQz0AEYBxVSF+FABJADveWkH6oAAAAAElFTkSuQmCC'

/**
 * Upload a tiny test image to the rig account's instance and return the
 * media id. Pixelfed answers `202 Accepted` (async processing); Mastodon
 * answers `200`. Both return the media id immediately, which is usable as a
 * `media_ids` entry on the very next status-create call.
 *
 * Throws on any non-2xx so a broken upload surfaces as a clear fixture
 * failure rather than a confusing downstream "empty status" rejection.
 */
export async function uploadTestImage(entry: RigAccount): Promise<string> {
  const bytes = Buffer.from(TINY_PNG_BASE64, 'base64')
  const form = new FormData()
  form.append('file', new Blob([bytes], { type: 'image/png' }), 'halflight-it.png')

  const resp = await fetch(`https://${entry.instance}/api/v2/media`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${entry.accessToken}`,
      Accept: 'application/json',
    },
    body: form,
  })

  if (resp.status !== 200 && resp.status !== 202) {
    throw new Error(`media upload failed: HTTP ${resp.status} ${await resp.text()}`)
  }
  const json = (await resp.json()) as { id?: string | number }
  if (json.id === undefined || json.id === null || String(json.id).length === 0) {
    throw new Error('media upload returned no id')
  }
  return String(json.id)
}
