import { Router, Response, NextFunction } from 'express'
import { authMiddleware, AuthRequest } from '../middleware/auth'
import { getAllTemplates, getTemplateById, getTemplatesByCategory, renderTemplate } from '../services/template.service'

const router = Router()

/** 获取所有模板列表 */
router.get('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const category = req.query.category as string | undefined
    const templates = category ? getTemplatesByCategory(category) : getAllTemplates()
    res.json({ success: true, data: templates })
  } catch (err) {
    next(err)
  }
})

/** 获取模板详情 */
router.get('/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const template = getTemplateById(req.params.id)
    if (!template) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '模板不存在' } })
    }
    res.json({ success: true, data: template })
  } catch (err) {
    next(err)
  }
})

/** 渲染模板 */
router.post('/:id/render', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const { variables } = req.body as { variables: Record<string, string> }
    const content = renderTemplate(req.params.id, variables || {})
    if (!content) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '模板不存在' } })
    }
    res.json({ success: true, data: { content } })
  } catch (err) {
    next(err)
  }
})

/** 下载模板（Word .doc 格式） */
router.get('/:id/download', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const template = getTemplateById(req.params.id)
    if (!template) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '模板不存在' } })
    }
    const encoded = encodeURIComponent(template.name + '.doc')
    res.setHeader('Content-Type', 'application/msword')
    res.setHeader('Content-Disposition', `attachment; filename="${encoded}"; filename*=UTF-8''${encoded}`)
    res.send(template.content)
  } catch (err) {
    next(err)
  }
})

export default router
