const router = require('express').Router()
const { ok, fail } = require('../lib/response')
const { requireUser } = require('../middleware/auth')
const { requireAdmin } = require('../middleware/auth')
const { getObjectUrl } = require('../lib/cos')
const firmwareDao = require('../dao/firmware.dao')
const logDao = require('../dao/log.dao')

const wrap = fn => (req, res, next) => fn(req, res, next).catch(next)

// NOTE: Admin firmware routes use /admin/firmware paths but are mounted at /api/v1
// (not under the /api/v1/admin router). This is intentional — firmware management is
// grouped in a single file alongside the user-facing /firmware/latest endpoint for
// cohesion, rather than splitting across the admin router and a separate user router.
// The requireAdmin middleware still protects these routes.

router.get('/admin/firmware', requireAdmin, wrap(async (req, res) => {
  const rows = await firmwareDao.list()
  res.json(ok({ records: rows, total: rows.length }))
}))

router.post('/admin/firmware', requireAdmin, wrap(async (req, res) => {
  const version = String(req.body.version || '').trim()
  const cosKey = String(req.body.cos_key || '').trim()
  if (!version || !cosKey) return res.json(fail(2001, 'version and cos_key required'))
  const result = await firmwareDao.create({
    version,
    device_type: req.body.device_type || '',
    cos_key: cosKey,
    size_bytes: Number(req.body.size_bytes || 0),
    sha256: req.body.sha256 || '',
    status: req.body.status === 0 ? 0 : 1
  })
  await logDao.write({ admin_id: req.admin.admin_id, action: 'admin_firmware_create', detail: '登记固件: ' + version, ip: req.ip })
  res.json(ok({ firmware_id: result.insertId }))
}))

router.post('/admin/firmware/:firmware_id/status', requireAdmin, wrap(async (req, res) => {
  const firmwareId = parseInt(req.params.firmware_id, 10)
  const status = Number(req.body.status) === 1 ? 1 : 0
  if (!firmwareId) return res.json(fail(2001, 'firmware_id required'))
  await firmwareDao.updateStatus(firmwareId, status)
  await logDao.write({ admin_id: req.admin.admin_id, action: 'admin_firmware_status', detail: '更新固件状态: ' + firmwareId + ' -> ' + status, ip: req.ip })
  res.json(ok({ message: 'success' }))
}))

router.get('/firmware/latest', requireUser, wrap(async (req, res) => {
  const firmware = await firmwareDao.findLatest()
  if (!firmware) return res.json(ok({ has_update: false }))
  const currentVersion = req.query.current_version || ''
  if (currentVersion && currentVersion === firmware.version) return res.json(ok({ has_update: false }))
  res.json(ok({
    has_update: true,
    version: firmware.version,
    size_bytes: firmware.size_bytes,
    sha256: firmware.sha256,
    download_url: await getObjectUrl(firmware.cos_key, 600)
  }))
}))

module.exports = router
