import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { createMitra, listMitras, updateMitraStatus } from '../../services/mitra.service.js'
import { getOnlineMitras, getOnlineLogs } from '../../services/mitra-status.service.js'
import { UserType } from '../../constants.js'

const attachCcUser = async (request, reply) => {
  if (request.auth?.userType !== UserType.CC_USER) {
    return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
  }
  const user = await getCcUserById(request.auth.userId)
  if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
  request.ccUser = user
}

export const mitraManagementRoutes = async (app) => {
  app.post('/', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'create')],
  }, async (request, reply) => {
    const { phone, display_name } = request.body ?? {}
    if (!phone || !display_name) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'phone and display_name are required' } })
    }
    const mitra = await createMitra({ phone, display_name })
    return reply.code(201).send({ success: true, data: mitra })
  })

  app.get('/', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'read')],
  }, async (request, reply) => {
    const { page = 1, limit = 20, is_active } = request.query
    const result = await listMitras({
      page: Number(page),
      limit: Number(limit),
      is_active: is_active !== undefined ? is_active === 'true' : undefined,
    })
    return reply.send({ success: true, data: result })
  })

  app.patch('/:id/status', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'update')],
  }, async (request, reply) => {
    const { is_active } = request.body ?? {}
    if (typeof is_active !== 'boolean') {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'is_active must be a boolean' } })
    }
    const mitra = await updateMitraStatus(request.params.id, is_active)
    return reply.send({ success: true, data: mitra })
  })

  app.get('/online', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'read')],
  }, async (request, reply) => {
    const mitras = await getOnlineMitras()
    return reply.send({ success: true, data: mitras })
  })

  app.get('/:id/online-logs', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'read')],
  }, async (request, reply) => {
    const { page = 1, limit = 50 } = request.query
    const result = await getOnlineLogs(request.params.id, { page: Number(page), limit: Number(limit) })
    return reply.send({ success: true, data: result })
  })
}
