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('/', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const fileType = req.query.fileType as string | undefined
    const files = await prisma.companyFile.findMany({
      where: { orgId: req.user!.orgId, ...(fileType ? { fileType } : {}) },
      orderBy: { createdAt: 'desc' },
    })
    res.json({ success: true, data: files })
  } catch (err) {
    next(err)
  }
})

// 添加公司文件记录
const companyFileSchema = z.object({
  fileName: z.string().min(1),
  fileType: z.enum(['BUSINESS_LICENSE', 'WORK_HOURS', 'HR_POLICY', 'LABOR_CONTRACT_TEMPLATE', 'OTHER']),
  fileUrl: z.string().min(1),
  fileSize: z.number().int().default(0),
  remark: z.string().optional(),
  expiryDate: z.string().optional(),
})

router.post('/', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const data = companyFileSchema.parse(req.body)
    const { expiryDate, ...rest } = data
    const file = await prisma.companyFile.create({
      data: {
        orgId: req.user!.orgId,
        ...rest,
        ...(expiryDate ? { expiryDate: new Date(expiryDate) } : {}),
        uploadedBy: req.user!.id,
      },
    })
    res.json({ success: true, data: file })
  } catch (err) {
    next(err)
  }
})

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

export default router
