import { authenticate } from '../../plugins/auth.js'
import { countAvailableMitrasFromCache } from '../../services/mitra-status.service.js'
import { UserType } from '../../constants.js'

/**
 * Customer-authed availability poll (kept for CC/debug callers that want the
 * raw count).
 *
 *   GET /api/client/mitra-availability  →  200 { available: bool, count: number }
 *
 * The customer home polls `/api/public/bestie/available` instead — that route
 * is unauthenticated and returns only the boolean, since SHome1st renders
 * before the user has any JWT (see `requirement/flow_customer.mermaid.md` §1).
 *
 * Backed by a 10s in-memory cache (see mitra-status.service.js) so DB load
 * stays bounded regardless of poller count. No rate limit by intent.
 */
export const clientMitraAvailabilityRoutes = async (app) => {
  app.get('/', { preHandler: [authenticate] }, async (request, reply) => {
    if (request.auth?.userType !== UserType.CUSTOMER) {
      return reply.code(403).send({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Customer account required' },
      })
    }
    const result = await countAvailableMitrasFromCache()
    return reply.send({ success: true, data: result })
  })
}
