import { authenticate } from '../../plugins/auth.js'
import { getMitraById } from '../../services/mitra.service.js'
import * as mitraStatusService from '../../services/mitra-status.service.js'
import * as valkey from '../../plugins/valkey.js'
import { VK_MITRAS_DEACTIVATED } from '../../services/mitra-status.service.js'
import { UserType } from '../../constants.js'

export const mitraStatusRoutes = async (app) => {
  const resolveMitra = async (request, reply) => {
    if (request.auth?.userType !== UserType.MITRA) {
      return reply.code(403).send({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Mitra account required' },
      })
    }
    const mitra = await getMitraById(request.auth.userId)
    if (!mitra) {
      return reply.code(404).send({
        success: false,
        error: { code: 'ACCOUNT_NOT_FOUND', message: 'Mitra account not found' },
      })
    }
    if (!mitra.is_active) {
      return reply.code(403).send({
        success: false,
        error: { code: 'ACCOUNT_INACTIVE', message: 'Account is inactive' },
      })
    }
    request.mitra = mitra
  }

  // Lightweight heartbeat guard: no Postgres SELECT in the hot path. Checks
  // `mitras:deactivated` in Valkey (maintained on every updateMitraStatus) and
  // falls back to the full resolveMitra/DB check if Valkey is unreachable so a
  // Valkey outage doesn't accept heartbeats from deactivated mitras silently.
  const heartbeatGuard = async (request, reply) => {
    if (request.auth?.userType !== UserType.MITRA) {
      return reply.code(403).send({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Mitra account required' },
      })
    }
    try {
      const deactivated = await valkey.sismember(VK_MITRAS_DEACTIVATED, request.auth.userId)
      if (deactivated) {
        return reply.code(403).send({
          success: false,
          error: { code: 'ACCOUNT_INACTIVE', message: 'Account is inactive' },
        })
      }
      return
    } catch (err) {
      console.warn('[heartbeat] valkey check failed, falling back to DB:', err.message)
      return resolveMitra(request, reply)
    }
  }

  app.post('/online', { preHandler: [authenticate, resolveMitra] }, async (request, reply) => {
    await mitraStatusService.setOnline(request.mitra.id)
    return reply.send({ success: true, data: { is_online: true } })
  })

  app.post('/offline', { preHandler: [authenticate, resolveMitra] }, async (request, reply) => {
    await mitraStatusService.setOffline(request.mitra.id)
    return reply.send({ success: true, data: { is_online: false } })
  })

  app.post('/heartbeat', { preHandler: [authenticate, heartbeatGuard] }, async (request, reply) => {
    await mitraStatusService.heartbeat(request.auth.userId)
    return reply.send({ success: true })
  })

  app.get('/', { preHandler: [authenticate, resolveMitra] }, async (request, reply) => {
    const status = await mitraStatusService.getStatus(request.mitra.id)
    return reply.send({ success: true, data: status })
  })
}
