const router = require('express').Router()
const { ok, fail } = require('../lib/response')
const { requireUser } = require('../middleware/auth')
const wxpay = require('../lib/wxpay')
const paymentOrderDao = require('../dao/payment-order.dao')
const logDao = require('../dao/log.dao')

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

// Query order status (user)
router.get('/payment/orders/:order_id', requireUser, wrap(async (req, res) => {
  const order = await paymentOrderDao.findByOutTradeNo(req.params.order_id)
  if (!order || order.user_id !== req.user.user_id) return res.json(fail(1005, 'order_not_found'))
  res.json(ok({
    order_id: order.order_id,
    plan: order.plan,
    amount_fen: order.amount_fen,
    status: order.status,
    paid_at: order.paid_at
  }))
}))

// Sync order — query WeChat and activate if paid (user)
router.post('/payment/orders/:order_id/sync', requireUser, wrap(async (req, res) => {
  const order = await paymentOrderDao.findByOutTradeNo(req.params.order_id)
  if (!order || order.user_id !== req.user.user_id) return res.json(fail(1005, 'order_not_found'))
  if (order.status === 'paid') return res.json(ok({ status: 'paid', message: 'already activated' }))

  if (!wxpay.isConfigured()) return res.json(fail(2001, 'payment not configured'))

  const wxOrder = await wxpay.queryOrder(order.order_id)
  if (wxOrder.trade_state === 'SUCCESS') {
    if (!wxOrder.amount || wxOrder.amount.total !== order.amount_fen) {
      return res.json(fail(2001, 'amount mismatch'))
    }
    await paymentOrderDao.markPaidAndActivateSubscription(order.order_id, wxOrder.transaction_id, wxOrder)
    await logDao.write({ user_id: order.user_id, action: 'payment_sync_success', detail: 'order: ' + order.order_id, ip: req.ip })
    return res.json(ok({ status: 'paid', message: 'subscription activated' }))
  }

  if (wxOrder.trade_state === 'CLOSED' || wxOrder.trade_state === 'REVOKED') {
    await paymentOrderDao.markClosed(order.order_id)
  } else if (wxOrder.trade_state === 'PAYERROR') {
    await paymentOrderDao.markFailed(order.order_id, wxOrder.trade_state)
  }

  res.json(ok({ status: order.status, trade_state: wxOrder.trade_state }))
}))

module.exports = router
