import type { RouteProductCode } from '@/types/db'

/**
 * Routing products (2026-09-29 Synchron purchasing task §5).
 *
 * The browser asks for a product by CODE; the backend resolves the price from
 * `routing_products`. This file only maps codes to the `route_type` the rest
 * of the app already uses (`service_requests.route_type`, `RouteType`).
 */

export type RouteType = 'express' | 'extended'

export const ROUTE_PRODUCT_CODES: readonly RouteProductCode[] = ['express_route', 'extended_route'] as const

const CODE_TO_TYPE: Record<RouteProductCode, RouteType> = {
  express_route: 'express',
  extended_route: 'extended',
}
const TYPE_TO_CODE: Record<RouteType, RouteProductCode> = {
  express: 'express_route',
  extended: 'extended_route',
}

export function isRouteProductCode(value: unknown): value is RouteProductCode {
  return typeof value === 'string' && (ROUTE_PRODUCT_CODES as readonly string[]).includes(value)
}

export function routeTypeForProduct(code: RouteProductCode): RouteType {
  return CODE_TO_TYPE[code]
}

export function productCodeForRouteType(type: RouteType): RouteProductCode {
  return TYPE_TO_CODE[type]
}

/** "$1.99" from 199. Display only — never used for arithmetic. */
export function formatCents(cents: number, currency = 'USD'): string {
  const amount = (cents / 100).toFixed(2)
  return currency === 'USD' ? `$${amount}` : `${amount} ${currency}`
}
