import { formatSuccessResponse } from '../utils/response.js'

export function globalResponseHandler(req, res, next) {
  const oldJson = res.json.bind(res)

  res.json = (data) => {
    if (!data) return oldJson(formatSuccessResponse(null))

    //  ถ้า code ไม่ใช่ 200 → ตั้ง HTTP status ให้ตรงกับ code
    if (data?.code && String(data.code) !== '200') {
      res.status(Number(data.code) || 400)
      return oldJson(data)
    }

    res.status(200)
    return oldJson(formatSuccessResponse(data))
  }

  next()
}
