import { createHmac } from 'node:crypto'

/**
 * Signing for calls the Workspace makes to Synchron's /api/v1/hha/* (contract
 * v0.2.0, rules confirmed by the Synchron CTO on 2026-10-18):
 *   - headers X-HHA-Timestamp (Unix seconds, decimal) and X-HHA-Signature
 *   - signature = lowercase hex HMAC-SHA256 of timestamp + "." + payload
 *   - payload = the exact raw body bytes; for GET: "GET " + path + "?" + raw
 *     query (the "?" stays even when the query is empty)
 *   - path starts with "/" and includes the /api/v1 prefix, no host or scheme
 *   - 300-second window; Synchron accepts the current or the next secret
 * Sign the exact string that is sent; never re-encode after signing.
 */
export interface HhaSignatureInput {
  method: string
  /** e.g. /api/v1/hha/route-purchases — must start with "/" and carry no host. */
  path: string
  /** Raw query without the leading "?" (GET only). */
  query?: string
  /** Exact raw body as sent (non-GET). */
  body?: string
  secret: string
  /** Unix seconds; defaults to now. */
  nowSeconds?: number
}

export function hhaSigningPayload(input: Pick<HhaSignatureInput, 'method' | 'path' | 'query' | 'body'>): string {
  if (!input.path.startsWith('/') || /^\/\//.test(input.path)) throw new Error('path must be a path, not a URL')
  return input.method.toUpperCase() === 'GET' ? `GET ${input.path}?${input.query ?? ''}` : input.body ?? ''
}

export function signHhaRequest(input: HhaSignatureInput): { 'X-HHA-Timestamp': string; 'X-HHA-Signature': string } {
  if (input.secret.length < 32) throw new Error('signing secret is missing or too short')
  const timestamp = String(Math.floor(input.nowSeconds ?? Date.now() / 1000))
  const signature = createHmac('sha256', input.secret).update(`${timestamp}.${hhaSigningPayload(input)}`).digest('hex')
  return { 'X-HHA-Timestamp': timestamp, 'X-HHA-Signature': signature }
}

/** Synchron's single error shape for every /api/v1/hha/* error. */
export interface SynchronApiError { error: string; message: string; requestId: string | null; details: Record<string, unknown> }

export function parseSynchronError(json: unknown): SynchronApiError | null {
  if (!json || typeof json !== 'object' || Array.isArray(json)) return null
  const r = json as Record<string, unknown>
  if (typeof r.error !== 'string' || !r.error) return null
  const details = r.details && typeof r.details === 'object' && !Array.isArray(r.details) ? r.details as Record<string, unknown> : {}
  return { error: r.error, message: typeof r.message === 'string' ? r.message : '', requestId: typeof r.request_id === 'string' ? r.request_id : null, details }
}
