import { COMMODITIES, DEAL_TYPES, STAGES, SORT_OPTIONS, type Commodity, type DealType, type Stage, type SortOption } from './constants'
import type { ListingFilter } from './types'

type Params = Record<string, string | string[] | undefined>

function str(params: Params, key: string): string | undefined {
  const v = params[key]
  const s = Array.isArray(v) ? v[0] : v
  return s && s.length > 0 ? s : undefined
}

function num(params: Params, key: string): number | undefined {
  const s = str(params, key)
  if (s === undefined) return undefined
  const n = Number(s)
  return Number.isFinite(n) ? n : undefined
}

export function parseSearchParams(params: Params): ListingFilter {
  const commodityRaw = str(params, 'commodity')
  const dealRaw = str(params, 'negocio')
  const stageRaw = str(params, 'etapa')
  const sortRaw = str(params, 'orden')
  const verificados = str(params, 'verificados')

  return {
    category: str(params, 'tipo'),
    commodity: COMMODITIES.includes(commodityRaw as Commodity) ? (commodityRaw as Commodity) : undefined,
    dealType: DEAL_TYPES.includes(dealRaw as DealType) ? (dealRaw as DealType) : undefined,
    stage: STAGES.includes(stageRaw as Stage) ? stageRaw : undefined,
    country: str(params, 'pais'),
    priceMin: num(params, 'precioMin'),
    priceMax: num(params, 'precioMax'),
    surfaceMin: num(params, 'superficieMin'),
    surfaceMax: num(params, 'superficieMax'),
    verifiedOnly: verificados === '1' || verificados === 'true',
    sort: SORT_OPTIONS.includes(sortRaw as SortOption) ? (sortRaw as SortOption) : 'recientes',
  }
}
