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

import { MeiliSearchFilterBuilder } from 'meilisearch-helper'
import { data } from 'react-router'

import { createSearch } from '@repo/util/meili'

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

  // Post-migration (users): rename `tenant_id` to `org_id`
  let builder = new MeiliSearchFilterBuilder().where('tenant_id', '=', orgid)

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

  return data(r)
}
