// Protocol wire gates.
//
// The "wire gates" are the per-protocol modifications to outbound HTTP
// requests that have nothing to do with endpoint shape — they live at the
// transport layer rather than the operation layer. Today there are two:
//
//   - `_pe=1` query param (Pixelfed extended response format)
//   - `X-PIXELFED-APP: 1` header (first-party app identification)
//
// Both are Pixelfed-only. Mastodon servers ignore unknown query params but
// emitting them is semantically wrong, makes request-log diffs noisier when
// troubleshooting, and tightens the coupling we want to dilute.
//
// `ApiContext` is the primary consumer — every authenticated request goes
// through it and inherits the gates from `accountType`. Two pre-auth call
// sites (login `verify_credentials` probe; Pixelfed-only signup endpoints)
// also need the gates but predate the existence of an `ApiContext`. They
// import these helpers directly so the gate logic stays in one place even
// when there is no `AccountStore` entry to read from.
//
// Adding a third protocol: extend the switch in each helper. TypeScript
// flags missing branches because `AccountType` is a discriminated union.

import type { AccountType } from 'src/state/accountStore'

/**
 * Apply protocol-specific URL query params to `url` in place.
 *
 * Today: appends `_pe=1` on Pixelfed; no-op on Mastodon.
 *
 * Mutates the URL rather than returning a new string so callers that already
 * hold a `URL` instance (the common case inside `ApiContext`) avoid a
 * round-trip through `toString()` + `new URL(...)`.
 */
export function applyProtocolUrlGates(url: URL, protocol: AccountType): void {
  if (protocol === 'pixelfed') {
    url.searchParams.set('_pe', '1')
  }
}

/**
 * Header fragment for the optional `X-PIXELFED-APP` first-party marker.
 *
 * Returns an empty object on Mastodon even when `enabled` is true — the
 * header would leak Pixelfed-internal naming to remote servers, and the
 * surfaces that opt in (`api/v1.1/push/*`, the legacy app-attributed flows)
 * are Pixelfed-only by construction. Mastodon callers should not need this
 * helper at all; the no-op return is defence-in-depth for shared call sites.
 *
 * Spread into a headers literal: `{ ...protocolAppHeader('pixelfed', true) }`.
 */
export function protocolAppHeader(
  protocol: AccountType,
  enabled: boolean
): Record<string, string> {
  if (enabled && protocol === 'pixelfed') {
    return { 'X-PIXELFED-APP': '1' }
  }
  return {}
}
