const Router = require('koa-router')
const multer = require('@koa/multer')
const path = require('path')
const fs = require('fs')

const router = new Router()

// 确保上传目录存在
const uploadDir = path.join(__dirname, '..', 'public', 'uploads')
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true })
}

// 配置 multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir)
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
    const ext = path.extname(file.originalname)
    cb(null, uniqueSuffix + ext)
  }
})

const upload = multer({ storage })

// 上传接口
router.post('/', upload.single('file'), async (ctx) => {
  if (!ctx.file) {
    ctx.status = 400
    ctx.body = {
      code: 400,
      message: '没有上传文件'
    }
    return
  }

  const fileUrl = `http://localhost:3000/uploads/${ctx.file.filename}`
  ctx.body = {
    code: 200,
    message: '上传成功',
    url: fileUrl
  }
})

module.exports = router.routes()
