import { authenticate } from '../../plugins/auth.js'
import { getMitraById } from '../../services/mitra.service.js'
import * as mitraStatusService 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
  }

  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, resolveMitra] }, async (request, reply) => {
    await mitraStatusService.heartbeat(request.mitra.id)
    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 })
  })
}
