import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { getMitraActivityLog, getMitraActivitySummary } from '../../services/mitra-activity.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 mitraActivityRoutes = async (app) => {
  app.get('/log', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'read')],
  }, async (request, reply) => {
    const { mitra_id, date_from, date_to, page = 1, limit = 20 } = request.query
    const result = await getMitraActivityLog({
      mitra_id, date_from, date_to,
      page: Number(page), limit: Number(limit),
    })
    return reply.send({ success: true, data: result })
  })

  app.get('/summary', {
    preHandler: [authenticate, attachCcUser, requirePermission('mitra', 'read')],
  }, async (request, reply) => {
    const { mitra_id, date_from, date_to } = request.query
    const result = await getMitraActivitySummary({ mitra_id, date_from, date_to })
    return reply.send({ success: true, data: result })
  })
}
