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

const router = Router()

function safeDecryptStr(encrypted: string | null): string | null {
  if (!encrypted) return null
  try {
    if (!encrypted.includes(':')) return encrypted
    return decrypt(encrypted)
  } catch { return null }
}

// 休假申请列表
router.get('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const orgId = req.user!.orgId
    const { status, leaveType, employeeId } = req.query
    const { page, pageSize } = parsePagination(req.query)

    const where: any = { orgId }
    if (status) where.status = status
    if (leaveType) where.leaveType = leaveType
    if (employeeId) where.employeeId = employeeId

    const total = await prisma.leaveRequest.count({ where })
    const list = await prisma.leaveRequest.findMany({
      where,
      include: {
        employee: { select: { id: true, name: true, department: true, position: true, idCardNumber: true } },
      },
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * pageSize,
      take: pageSize,
    })

    const data = list.map((r: any) => ({
      ...r,
      employee: r.employee ? { ...r.employee, idCardNumber: safeDecryptStr(r.employee.idCardNumber) } : r.employee,
    }))
    res.json({ success: true, data: { list: data, total, page, pageSize } })
  } catch (err) {
    next(err)
  }
})

// 创建休假申请
router.post('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const orgId = req.user!.orgId
    const { employeeId, leaveType, startDate, endDate, days, reason, attachment } = req.body

    if (!employeeId || !leaveType || !startDate || !endDate) {
      return res.status(400).json({ success: false, error: { code: 'BAD_REQUEST', message: '缺少必填字段' } })
    }

    const record = await prisma.leaveRequest.create({
      data: {
        orgId,
        employeeId,
        leaveType,
        startDate: new Date(startDate),
        endDate: new Date(endDate),
        days: days || 1,
        reason: reason || null,
        attachment: attachment || null,
        createdBy: req.user!.id,
      },
      include: {
        employee: { select: { id: true, name: true, department: true, position: true } },
      },
    })

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

// 审批（批准/驳回）
router.post('/:id/approve', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params
    const { action, remark } = req.body // action: 'APPROVED' | 'REJECTED'
    const orgId = req.user!.orgId

    if (!['APPROVED', 'REJECTED'].includes(action)) {
      return res.status(400).json({ success: false, error: { code: 'BAD_REQUEST', message: '无效的审批操作' } })
    }

    const existing = await prisma.leaveRequest.findFirst({ where: { id, orgId } })
    if (!existing) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '申请不存在' } })
    }
    if (existing.status !== 'PENDING') {
      return res.status(400).json({ success: false, error: { code: 'BAD_REQUEST', message: '该申请已处理' } })
    }

    const updated = await prisma.leaveRequest.update({
      where: { id },
      data: {
        status: action,
        approverId: req.user!.id,
        approvedAt: new Date(),
        approveRemark: remark || null,
      },
      include: {
        employee: { select: { id: true, name: true, department: true, position: true } },
      },
    })

    // 如果批准，自动创建 LeaveRecord
    if (action === 'APPROVED') {
      await prisma.leaveRecord.create({
        data: {
          orgId,
          employeeId: existing.employeeId,
          leaveType: existing.leaveType,
          startDate: existing.startDate,
          endDate: existing.endDate,
          days: existing.days,
          reason: existing.reason || '',
          remark: `休假审批通过（申请ID: ${id}）`,
          createdBy: req.user!.id,
        },
      })
    }

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

// 撤回申请
router.post('/:id/cancel', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params
    const orgId = req.user!.orgId

    const existing = await prisma.leaveRequest.findFirst({ where: { id, orgId } })
    if (!existing) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '申请不存在' } })
    }
    if (existing.status !== 'PENDING') {
      return res.status(400).json({ success: false, error: { code: 'BAD_REQUEST', message: '已处理的申请不可撤回' } })
    }

    const updated = await prisma.leaveRequest.update({
      where: { id },
      data: { status: 'CANCELLED' },
    })

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

// 删除申请（仅待审批状态可删）
router.delete('/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params
    const orgId = req.user!.orgId

    const existing = await prisma.leaveRequest.findFirst({ where: { id, orgId } })
    if (!existing) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '申请不存在' } })
    }
    if (existing.status !== 'PENDING') {
      return res.status(400).json({ success: false, error: { code: 'BAD_REQUEST', message: '已处理的申请不可删除' } })
    }

    await prisma.leaveRequest.delete({ where: { id } })
    res.json({ success: true })
  } catch (err) {
    next(err)
  }
})

// 统计
router.get('/stats', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const orgId = req.user!.orgId
    const { month } = req.query

    const where: any = { orgId }
    if (month) {
      const start = new Date(`${month}-01`)
      const end = new Date(`${month}-31T23:59:59`)
      where.startDate = { gte: start, lte: end }
    }

    const [pending, approved, rejected, cancelled, total] = await Promise.all([
      prisma.leaveRequest.count({ where: { ...where, status: 'PENDING' } }),
      prisma.leaveRequest.count({ where: { ...where, status: 'APPROVED' } }),
      prisma.leaveRequest.count({ where: { ...where, status: 'REJECTED' } }),
      prisma.leaveRequest.count({ where: { ...where, status: 'CANCELLED' } }),
      prisma.leaveRequest.count({ where }),
    ])

    res.json({ success: true, data: { pending, approved, rejected, cancelled, total } })
  } catch (err) {
    next(err)
  }
})

export default router
