import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { listSessions, getSessionById, rerouteSession } from '../../services/session.service.js'
import { getSessionSensitivityLog } from '../../services/sensitivity.service.js'
import { getDashboardStats } from '../../services/dashboard.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 sessionManagementRoutes = async (app) => {
  app.get('/dashboard/stats', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const stats = await getDashboardStats()
    return reply.send({ success: true, data: stats })
  })

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

  app.get('/:sessionId', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const session = await getSessionById(request.params.sessionId)
    if (!session) {
      return reply.code(404).send({ success: false, error: { code: 'NOT_FOUND', message: 'Session not found' } })
    }
    const sensitivity_log = await getSessionSensitivityLog(request.params.sessionId)
    return reply.send({ success: true, data: { ...session, sensitivity_log } })
  })

  app.post('/:sessionId/reroute', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { new_mitra_id } = request.body ?? {}
    if (!new_mitra_id) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'new_mitra_id is required' } })
    }
    const session = await rerouteSession(request.params.sessionId, new_mitra_id)
    return reply.send({ success: true, data: session })
  })
}
