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

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

  if (!table || !segmentParam) {
    throw createError({ statusCode: 400, statusMessage: 'Tabla o parámetro no especificados' })
  }

  const values = Array.isArray(segmentParam) ? segmentParam : [segmentParam]
  const target = values[0]

  const parsedQuery = parseQuerySegment(target)

  if (parsedQuery) {
    return await fetchTableData(table, { parsedQuery })
  }

  return await fetchTableRecord(table, target)
})
