import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { listFailures, setOperatorAction } from '../../services/pairing-failure.service.js'
import { UserType, PairingFailureCause, PairingFailureOperatorAction } 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
}

const VALID_CAUSE_TAGS = new Set(Object.values(PairingFailureCause))
const VALID_ACTIONS = new Set(Object.values(PairingFailureOperatorAction))

/**
 * Control-center "Failed Pairings" review screen backend.
 *
 *   GET  /internal/failed-pairings
 *   POST /internal/failed-pairings/:id/action
 */
export const failedPairingsRoutes = async (app) => {
  app.get('/', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const { cause_tags, date_from, date_to, limit = 50, offset = 0 } = request.query ?? {}

    // cause_tags can arrive as a single string (?cause_tags=foo) or an array
    // (?cause_tags=foo&cause_tags=bar). Normalize and validate.
    let causeTagsArr = null
    if (cause_tags !== undefined) {
      causeTagsArr = Array.isArray(cause_tags) ? cause_tags : [cause_tags]
      for (const tag of causeTagsArr) {
        if (!VALID_CAUSE_TAGS.has(tag)) {
          return reply.code(422).send({
            success: false,
            error: { code: 'VALIDATION_ERROR', message: `Unknown cause_tag: ${tag}` },
          })
        }
      }
    }

    const result = await listFailures({
      causeTags: causeTagsArr,
      dateFrom: date_from || null,
      dateTo: date_to || null,
      limit: Number(limit) || 50,
      offset: Number(offset) || 0,
    })

    return reply.send({ success: true, data: result })
  })

  app.post('/:id/action', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { action } = request.body ?? {}
    if (!VALID_ACTIONS.has(action)) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: `action must be one of: ${[...VALID_ACTIONS].join(', ')}` },
      })
    }
    const updated = await setOperatorAction(request.params.id, request.ccUser.id, action)
    return reply.send({ success: true, data: updated })
  })
}
