import { PikkuRPC } from '@project/functions-sdk/pikku/pikku-rpc.gen'
import { apiUrl } from './env'

// The Pikku-RPC shim. `rpc.invoke` is typed by the generated FlattenedRPCMap, so
// `makeApi().invoke('listCards', input)` checks the name and payload at compile
// time. Pikku emits unversioned latest-aliases (`listCards` → `listCards@v2`),
// so you call clean names. Used from TanStack Start loaders (SSR + client) and
// from event handlers for mutations.
export function makeApi(): PikkuRPC {
  const rpc = new PikkuRPC()
  rpc.setServerUrl(apiUrl())
  return rpc
}

export async function formatApiError(error: unknown): Promise<string> {
  if (error instanceof Response) {
    const status = [error.status, error.statusText].filter(Boolean).join(' ')

    try {
      const payload = (await error.clone().json()) as {
        message?: unknown
        errorId?: unknown
      }
      if (typeof payload?.message === 'string') {
        const detail =
          typeof payload.errorId === 'string'
            ? `${payload.message} (${payload.errorId})`
            : payload.message
        return status ? `${status}: ${detail}` : detail
      }
    } catch {
      // Fall through to plain text/body-less formatting.
    }

    try {
      const text = (await error.clone().text()).trim()
      if (text) return status ? `${status}: ${text}` : text
    } catch {
      // Ignore body-read failures and fall through.
    }

    return status || 'Request failed'
  }

  return error instanceof Error ? error.message : String(error)
}
