import { verifyToken } from '../utils/token.js'
import { sendError } from '../utils/response.js'

export function authMiddleware(req, res, next) {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]
  if (!token) return sendError('ไม่พบ Token', 'Missing token', 401)

  const decoded = verifyToken(token)
  if (!decoded) return sendError('Token ไม่ถูกต้อง', 'Invalid token', 403)

  req.user = decoded
  next()
}
