import { Router } from 'express'

import { deleteWorkerSession, getWorkerSessions } from '../../services/worker-platform/index.js'
import { getRequiredWorkerSession } from './session.js'
import { createRouteHandler } from '../../utils/http.js'
import { openWorkerRealtimeStream } from '../../services/realtime/realtime-event-service.js'

const router = Router()

router.get(
  '/auth/devices',
  createRouteHandler((req) => getWorkerSessions(getRequiredWorkerSession(req)), {
    successMessage: 'ok',
    errorMessage: '读取登录设备失败',
    scope: '[worker/auth/devices]',
  }),
)

router.delete(
  '/auth/devices/:sessionId',
  createRouteHandler(
    (req) => deleteWorkerSession(getRequiredWorkerSession(req), req.params.sessionId),
    {
      successMessage: '登录设备已删除',
      errorMessage: '删除登录设备失败',
      scope: '[worker/auth/devices/delete]',
    },
  ),
)

router.get('/realtime', (req, res) => {
  openWorkerRealtimeStream(
    res,
    getRequiredWorkerSession(req).workerId,
    Number(req.get('Last-Event-ID') || req.query.lastEventId || 0) || 0,
  )
})

export default router
