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

/**
 * Customer-home availability poll.
 *
 *   GET /api/client/mitra-availability  →  200 { available: bool, count?: number }
 *
 * Hot endpoint by design — polled every 5s per active customer while their home is
 * foregrounded. 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.
 *
 * `count` is included for CC/debug; the customer UI must read only `available`.
 */
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 })
  })
}
