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

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

// 获取员工附件列表
router.get('/:employeeId', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const attachments = await prisma.employeeAttachment.findMany({
      where: { orgId: req.user!.orgId, employeeId: req.params.employeeId },
      orderBy: { createdAt: 'desc' },
    })
    res.json({ success: true, data: attachments })
  } catch (err) {
    next(err)
  }
})

// 添加附件记录（文件URL由前端上传后传入）
const attachmentSchema = z.object({
  employeeId: z.string().min(1),
  fileName: z.string().min(1),
  fileType: z.enum(['ID_CARD', 'BANK_CARD', 'CONTRACT_SCAN', 'EDUCATION', 'TERMINATION_DOC', 'RETIREMENT_DOC', 'INJURY_CERT', 'MEDICAL_CERT', 'PREGNANCY_CERT', 'DISCIPLINARY', 'OTHER']),
  fileUrl: z.string().min(1),
  fileSize: z.number().int().default(0),
})

router.post('/', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const data = attachmentSchema.parse(req.body)
    const attachment = await prisma.employeeAttachment.create({
      data: {
        orgId: req.user!.orgId,
        ...data,
        uploadedBy: req.user!.id,
      },
    })
    res.json({ success: true, data: attachment })
  } catch (err) {
    next(err)
  }
})

// 删除附件
router.delete('/:id', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const attachment = await prisma.employeeAttachment.findFirst({
      where: { id: req.params.id, orgId: req.user!.orgId },
    })
    if (!attachment) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '附件不存在' } })
    }
    await prisma.employeeAttachment.delete({ where: { id: attachment.id } })
    res.json({ success: true })
  } catch (err) {
    next(err)
  }
})

export default router
