import { Router, Response, NextFunction } from 'express'
import { authMiddleware, AuthRequest } from '../middleware/auth'
import { getEvidenceByRef, getEvidenceByEmployee, getEvidenceDetail, verifyEvidence, getEvidenceList, verifyAllEvidence } from '../services/evidence.service'

const router = Router()

/**
 * 获取组织级证据链列表
 * GET /api/v1/evidence?category=ALL&page=1&pageSize=20
 */
router.get('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const category = (req.query.category as string) || 'ALL'
    const page = parseInt(req.query.page as string) || 1
    const pageSize = Math.min(parseInt(req.query.pageSize as string) || 20, 200)
    const data = await getEvidenceList(req.user!.orgId, category, page, pageSize)
    res.json({ success: true, data })
  } catch (err) {
    next(err)
  }
})

/**
 * 验证全部证据链完整性
 * GET /api/v1/evidence/verify-all
 */
router.get('/verify-all', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const data = await verifyAllEvidence(req.user!.orgId)
    res.json({ success: true, data })
  } catch (err) {
    next(err)
  }
})

/**
 * 获取某操作的完整证据链
 * GET /api/v1/evidence/:category/:refId
 */
router.get('/:category/:refId', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const evidence = await getEvidenceByRef(req.user!.orgId, req.params.category, req.params.refId)
    res.json({ success: true, data: evidence })
  } catch (err) {
    next(err)
  }
})

/**
 * 获取某员工所有证据链
 * GET /api/v1/evidence/employee/:id
 */
router.get('/employee/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const evidence = await getEvidenceByEmployee(req.user!.orgId, req.params.id)
    res.json({ success: true, data: evidence })
  } catch (err) {
    next(err)
  }
})

/**
 * 获取证据链详情
 * GET /api/v1/evidence/detail/:id
 */
router.get('/detail/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const evidence = await getEvidenceDetail(req.user!.orgId, req.params.id)
    res.json({ success: true, data: evidence })
  } catch (err) {
    next(err)
  }
})

/**
 * 验证证据链完整性
 * GET /api/v1/evidence/verify/:id
 */
router.get('/verify/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const result = await verifyEvidence(req.user!.orgId, req.params.id)
    res.json({ success: true, data: result })
  } catch (err) {
    next(err)
  }
})

export default router
