import { parseQuerySegment } from '../../../services/query-parser'
import { fetchTableData } from '../../../services/table-service'

export default defineEventHandler(async (event) => {
  const table = event.context.params?.table

  if (!table) {
    throw createError({ statusCode: 400, statusMessage: 'Tabla no especificada' })
  }

  const query = getQuery(event)
  const limitValue = Number.parseInt((query.limit as string) ?? '', 10)
  const limit = Number.isFinite(limitValue) ? Math.min(Math.max(limitValue, 1), 500) : undefined

  const parsedQuery = parseQuerySegment(query.query as string | undefined)

  return await fetchTableData(table, {
    parsedQuery,
    limit,
    filters: {
      id: (query.id as string) || undefined,
      createdFrom: (query.created_from as string) || undefined,
      createdTo: (query.created_to as string) || undefined
    }
  })
})
