import { Router, Response, NextFunction } from 'express'
import prisma from '../lib/prisma'
import { authMiddleware, AuthRequest } from '../middleware/auth'

const router = Router()
router.use(authMiddleware)

/**
 * 查询审计日志
 * 支持按操作类型、实体类型、时间范围筛选
 */
router.get('/', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const page = parseInt(req.query.page as string) || 1
    const pageSize = Math.min(parseInt(req.query.pageSize as string) || 20, 200)
    const action = req.query.action as string | undefined
    const entity = req.query.entity as string | undefined
    const userId = req.query.userId as string | undefined
    const dateFrom = req.query.dateFrom as string | undefined
    const dateTo = req.query.dateTo as string | undefined

    const where: any = { orgId: req.user!.orgId }
    if (action) where.action = { contains: action, mode: 'insensitive' }
    if (entity) where.entity = entity
    if (userId) where.userId = userId
    if (dateFrom || dateTo) {
      where.createdAt = {}
      if (dateFrom) where.createdAt.gte = new Date(dateFrom)
      if (dateTo) where.createdAt.lte = new Date(`${dateTo}T23:59:59`)
    }

    const [logs, total] = await Promise.all([
      prisma.auditLog.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
      prisma.auditLog.count({ where }),
    ])

    res.json({
      success: true,
      data: { items: logs, total, page, pageSize, totalPages: Math.ceil(total / pageSize) },
    })
  } catch (err) {
    next(err)
  }
})

/**
 * 获取审计日志统计（按操作类型分组）
 */
router.get('/stats', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const dateFrom = req.query.dateFrom as string | undefined
    const dateTo = req.query.dateTo as string | undefined

    const where: any = { orgId: req.user!.orgId }
    if (dateFrom || dateTo) {
      where.createdAt = {}
      if (dateFrom) where.createdAt.gte = new Date(dateFrom)
      if (dateTo) where.createdAt.lte = new Date(`${dateTo}T23:59:59`)
    }

    const stats = await prisma.auditLog.groupBy({
      by: ['action'],
      where,
      _count: { action: true },
      orderBy: { _count: { action: 'desc' } },
      take: 20,
    })

    res.json({ success: true, data: stats })
  } catch (err) {
    next(err)
  }
})

export default router
