const router = require('express').Router()
const { ok, fail } = require('../lib/response')
const { requireUser } = require('../middleware/auth')
const { toMysqlDate } = require('../lib/utils')
const treatmentDao = require('../dao/treatment.dao')
const bindingDao = require('../dao/binding.dao')
const logDao = require('../dao/log.dao')

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

router.get('/treatment/history', requireUser, wrap(async (req, res) => {
  const page = Math.max(1, parseInt(req.query.page, 10) || 1)
  const pageSize = Math.min(Math.max(1, parseInt(req.query.page_size, 10) || 20), 100)
  const offset = (page - 1) * pageSize
  const { records, total } = await treatmentDao.listByUser(req.user.user_id, { pageSize, offset })
  res.json(ok({ total, page, page_size: pageSize, records }))
}))

router.post('/treatment/sync', requireUser, wrap(async (req, res) => {
  const d = req.body || {}
  if (!d.device_id) return res.json(fail(2001, 'device_id required'))

  const active = await bindingDao.findActiveByUser(req.user.user_id)
  if (!active || String(active.device_id) !== String(d.device_id)) return res.json(fail(1006, 'device_not_bound'))

  const sessionId = d.session_id || 'SESS' + Date.now()
  await treatmentDao.create({
    session_id: sessionId,
    device_id: d.device_id,
    user_id: req.user.user_id,
    start_time: toMysqlDate(d.start_time),
    end_time: toMysqlDate(d.end_time),
    regions: Array.isArray(d.regions) ? d.regions.join(',') : String(d.regions || ''),
    total_duration_ms: parseInt(d.total_duration_ms, 10) || 0,
    mode: parseInt(d.mode, 10) || 0,
    avg_pd: Number(d.avg_pd) || 0,
    battery: d.battery == null ? null : parseInt(d.battery, 10),
    temperature: d.temperature == null ? null : parseInt(d.temperature, 10),
    wavelength: d.wavelength == null ? null : parseInt(d.wavelength, 10),
    brightness: d.brightness == null ? null : parseInt(d.brightness, 10),
    pd_json: JSON.stringify(d.pd_values || {})
  })
  await treatmentDao.updateDevice(
    d.device_id,
    d.battery == null ? null : parseInt(d.battery, 10),
    d.temperature == null ? null : parseInt(d.temperature, 10)
  )
  await logDao.write({ user_id: req.user.user_id, action: 'treatment_sync', detail: '同步使用记录: ' + sessionId, ip: req.ip })
  res.json(ok({ record_id: sessionId }))
}))

router.get('/treatment/:record_id', requireUser, wrap(async (req, res) => {
  const record = await treatmentDao.findBySession(req.params.record_id, req.user.user_id)
  if (!record) return res.json(fail(1005, 'record_not_found'))
  res.json(ok(record))
}))

module.exports = router
