const jwt = require('jsonwebtoken')
const config = require('../config')
const { one } = require('../lib/db')
const { readBearer } = require('../lib/auth')

function authMiddleware(req, res, next) {
  req.ip = req.headers['x-forwarded-for']
    ? req.headers['x-forwarded-for'].split(',')[0].trim()
    : req.ip || ''
  next()
}

async function requireUser(req, res, next) {
  const token = readBearer(req.headers)
  if (!token) return res.status(401).json({ code: 1001, message: 'invalid_token', data: {} })
  try {
    const payload = jwt.verify(token, config.jwt.secret)
    if (payload.type !== 'user') return res.status(401).json({ code: 1001, message: 'invalid_token', data: {} })
    req.user = await one('SELECT * FROM users WHERE user_id = :user_id AND status = 1', { user_id: payload.user_id })
    if (!req.user) return res.status(401).json({ code: 1001, message: 'invalid_token', data: {} })
    next()
  } catch (err) {
    return res.status(401).json({ code: 1001, message: 'invalid_token', data: {} })
  }
}

async function requireAdmin(req, res, next) {
  const token = readBearer(req.headers)
  if (!token) return res.status(401).json({ code: 1002, message: '未授权，请重新登录', data: {} })
  try {
    const payload = jwt.verify(token, config.jwt.adminSecret)
    if (payload.type !== 'admin') return res.status(401).json({ code: 1002, message: '未授权，请重新登录', data: {} })
    req.admin = await one('SELECT * FROM admin_accounts WHERE admin_id = :admin_id AND status = 1', { admin_id: payload.admin_id })
    if (!req.admin) return res.status(401).json({ code: 1002, message: '未授权，请重新登录', data: {} })
    next()
  } catch (err) {
    return res.status(401).json({ code: 1002, message: '未授权，请重新登录', data: {} })
  }
}

module.exports = { authMiddleware, requireUser, requireAdmin, readBearer }
