/**
 * Public API error envelope — tenant-public-api (wave-11 leaf-D).
 * Consistent error shape for all /v1/* responses.
 */

export interface ApiError {
  error: string
  message: string
  field?: string
  required?: string
  minimum_tier?: string
  retry_after?: number
}

export interface ApiErrorResponse {
  status: number
  body: ApiError
}

export function jsonError(status: number, body: ApiError): Response {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json' },
  })
}

// ── Named constructors ────────────────────────────────────────────────────────

export function errUnauthorized(message = 'API key missing or invalid'): Response {
  return jsonError(401, { error: 'unauthorized', message })
}

export function errForbiddenScope(requiredScope: string): Response {
  console.warn('insufficient_scope', { required: requiredScope })
  return jsonError(403, {
    error: 'insufficient_scope',
    message: 'Insufficient scope for this operation',
  })
}

export function errTierRequired(minimumTier: string): Response {
  return jsonError(403, {
    error: 'tier_required',
    message: `This endpoint requires the '${minimumTier}' plan or higher`,
    minimum_tier: minimumTier,
  })
}

export function errNotFound(resource = 'Resource'): Response {
  return jsonError(404, { error: 'not_found', message: `${resource} not found` })
}

export function errValidation(message: string, field?: string): Response {
  return jsonError(422, { error: 'validation_error', message, field })
}

export function errRateLimited(retryAfter: number): Response {
  return jsonError(429, {
    error: 'rate_limited',
    message: 'Too many requests. Please retry after the specified delay.',
    retry_after: retryAfter,
  })
}

export function errInternal(message = 'Internal server error'): Response {
  return jsonError(500, { error: 'internal_error', message })
}
