import type { Route } from './+types/route'

import { createSearch } from '@repo/util/meili'
import { data } from 'react-router'

export async function loader({ context, request }: Route.LoaderArgs) {
  const { searchParams } = new URL(request.url)
  const query = searchParams.get('q') || ''
  const page = Number(searchParams.get('p')) + 1
  const hitsPerPage = Number(searchParams.get('perPage')) || 25

  const r = await createSearch({
    index: 'betaeducacao-prod-users_d2o3r5gmm4it7j',
    sort: ['createDate:desc', 'create_date:desc'],
    filter: 'cnpj EXISTS',
    query,
    page,
    hitsPerPage,
    env: context.cloudflare.env
  })

  return data(r)
}
