/**
 * @softize/opus/server — shared helpers for server drivers.
 *
 * Drivers (Fastify, Hono, etc) consomem este módulo pra:
 *   - mapear ActionError.category → HTTP status
 *   - derivar route path + method de uma ActionDef
 *   - serializar ActionResult em response body
 *
 * Lógica específica de driver (registro de rotas, parsing de request) vive
 * em `src/drivers/<driver>.ts`.
 */

import type {
  ActionDef,
  ActionError,
  ActionResult,
  ErrorCategory,
  TraceContext,
} from '../core/index.ts'

// =============================================================================
// W3C trace context
// =============================================================================

export type HttpHeaderValue = string | string[] | undefined

/** Extrai somente traceparent v00 válido; tracestate é opcional e limitado a 512 bytes. */
export function extractW3CTraceContext(
  headers: Record<string, HttpHeaderValue>,
): TraceContext | undefined {
  const raw = firstHeader(headers['traceparent'])
  if (raw === undefined) return undefined
  const match = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i.exec(raw.trim())
  if (match === null) return undefined
  const traceId = match[1]?.toLowerCase()
  const spanId = match[2]?.toLowerCase()
  const flags = match[3]
  if (traceId === undefined || spanId === undefined || flags === undefined) return undefined
  if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined
  const traceState = validTraceState(firstHeader(headers['tracestate']))
  return {
    traceId,
    spanId,
    traceFlags: Number.parseInt(flags, 16),
    ...(traceState !== undefined ? { traceState } : {}),
  }
}

export function w3cTraceResponseHeaders(
  traceContext: TraceContext | undefined,
): Record<string, string> {
  if (traceContext === undefined || !validTraceIds(traceContext)) return {}
  const flags = (traceContext.traceFlags ?? 0) & 0xff
  return {
    traceparent: `00-${traceContext.traceId}-${traceContext.spanId}-${flags.toString(16).padStart(2, '0')}`,
    ...(validTraceState(traceContext.traceState) !== undefined
      ? { tracestate: traceContext.traceState as string }
      : {}),
  }
}

function firstHeader(value: HttpHeaderValue): string | undefined {
  return Array.isArray(value) ? (value.length === 1 ? value[0] : undefined) : value
}

function validTraceState(value: string | undefined): string | undefined {
  if (value === undefined || value.length === 0 || value.length > 512) return undefined
  return /[^\x20-\x7e]/.test(value) ? undefined : value
}

function validTraceIds(value: TraceContext): value is TraceContext & { spanId: string } {
  return /^[0-9a-f]{32}$/i.test(value.traceId) && !/^0+$/.test(value.traceId) &&
    typeof value.spanId === 'string' && /^[0-9a-f]{16}$/i.test(value.spanId) &&
    !/^0+$/.test(value.spanId)
}

// =============================================================================
// HTTP status mapping
// =============================================================================

/**
 * Mapping default `ErrorCategory` → HTTP status code.
 * Ver §3 do protocolo.
 */
const DEFAULT_HTTP_STATUS: Record<ErrorCategory, number> = {
  validation: 400,
  authentication: 401,
  authorization: 403,
  not_found: 404,
  conflict: 409,
  rate_limit: 429,
  dependency: 502,
  internal: 500,
}

/**
 * Retorna o HTTP status code apropriado pra um `ActionError`.
 */
export function httpStatusFor(error: ActionError): number {
  return DEFAULT_HTTP_STATUS[error.category]
}

/**
 * Retorna o HTTP status pra success result. Default 200; action pode
 * declarar `successStatus` (ex: 201 pra create).
 */
export function successStatusFor(action: ActionDef): number {
  return action.successStatus ?? 200
}

// =============================================================================
// Route convention
// =============================================================================

/**
 * Método HTTP padrão por kind:
 *   - simple, form → POST (mutações tipicamente)
 *   - search, view → GET (leitura)
 */
export type HttpMethod = 'GET' | 'POST'

export function methodFor(action: ActionDef): HttpMethod {
  return action.kind === 'simple' || action.kind === 'form' ? 'POST' : 'GET'
}

/**
 * Path derivado do nome da action. Converte dots em segments.
 *   - 'deal.archive'        → '/deal/archive'
 *   - 'crm.deal.list'       → '/crm/deal/list'
 *   - 'auth.sessionRefresh' → '/auth/sessionRefresh'
 *
 * `prefix` adicionado se passado (default '/api').
 */
export function pathFor(action: ActionDef, prefix = '/api'): string {
  const segments = action.name.split('.').map(encodeURIComponent)
  return `${prefix}/${segments.join('/')}`
}

/** A lista declara exportação (ADR 0069) e, portanto, ganha a rota de exportação. */
export function isExportableList(action: ActionDef): boolean {
  return action.kind === 'list' && action.export === true
}

/** Os valores como a query string os leva: texto, sem nulos. A rota de leitura de uma lista recebe
 *  o input assim, e a exportação o normaliza do mesmo jeito para o schema ver a mesma coisa. */
export function queryValues(input: Record<string, unknown>): Record<string, string> {
  const out: Record<string, string> = {}
  for (const [key, value] of Object.entries(input)) {
    if (value === undefined || value === null) continue
    out[key] = String(value)
  }
  return out
}

/** O pedido de exportação com o input normalizado como a query da rota de leitura. */
export function normalizeExportRequest(request: unknown): unknown {
  if (request === null || typeof request !== 'object') return request
  const input = (request as { input?: unknown }).input
  if (input === null || typeof input !== 'object' || Array.isArray(input)) return request
  return { ...request, input: queryValues(input as Record<string, unknown>) }
}

/** Rota de exportação de uma lista: a rota da action seguida de `/export`, sempre por POST. */
export function exportPathFor(action: ActionDef, prefix = '/api'): string {
  return `${pathFor(action, prefix)}/export`
}

// =============================================================================
// Body shape
// =============================================================================

/**
 * Decide se o input vem do body (POST) ou query string (GET).
 * Drivers usam pra extrair input do request.
 */
export function inputSourceFor(action: ActionDef): 'body' | 'query' {
  return methodFor(action) === 'POST' ? 'body' : 'query'
}

// =============================================================================
// Result serialization
// =============================================================================

/**
 * Envelope JSON-serializável de `ActionResult`. Driver chama `JSON.stringify`
 * direto no retorno desta função.
 *
 * `cause` em error é serializado como string (ver §3 do protocolo).
 */
export function serializeResult<T>(result: ActionResult<T>): unknown {
  if (result.ok) {
    return { ok: true, data: result.data, meta: result.meta }
  }
  return {
    ok: false,
    error: serializeError(result.error),
    meta: result.meta,
  }
}

function serializeError(err: ActionError): Record<string, unknown> {
  const out: Record<string, unknown> = {
    code: err.code,
    category: err.category,
    message: err.message,
    severity: err.severity,
    retriable: err.retriable,
  }
  if (err.i18nKey !== undefined) out.i18nKey = err.i18nKey
  if (err.i18nParams !== undefined) out.i18nParams = err.i18nParams
  if (err.field !== undefined) out.field = err.field
  if (err.issues !== undefined) out.issues = err.issues
  // Erro interno não leva `cause` para a wire: é o texto cru da exceção (driver, SQL), que
  // pertence ao log do servidor, não à pessoa nem ao cliente.
  if (err.cause !== undefined && err.category !== 'internal') out.cause = String(err.cause)
  if (err.meta !== undefined) out.meta = err.meta
  return out
}

// =============================================================================
// Internal action filter
// =============================================================================

/**
 * Actions com `internal: true` não são expostas via REST público.
 * Driver checa antes de chamar mount().
 */
export function shouldMountPublicly(action: ActionDef): boolean {
  return action.internal !== true
}
