const { getUserFromRequest } = require('../utils/auth')
const settings = require('../model/settings/settings.model')

const log = require('../utils/logger')('sitemode')

/**
 * Gate for public *content* routes (posts, wiki). When the site is in maintenance
 * mode, respond 503 with the maintenance message — UNLESS the request carries a
 * valid admin token (admin "preview live"). Settings/status/contact are not gated,
 * so the client can always fetch the maintenance message to render the page.
 */
async function siteMode(req, res, next) {
  try {
    const mode = await settings.get('site_mode')
    if (mode !== 'maintenance') return next()

    // Authenticated admins bypass the gate so they can preview the live site.
    if (getUserFromRequest(req)) return next()

    log.debug('blocked request (maintenance mode)', { path: req.originalUrl, ip: req.ip })
    const message = await settings.get('maintenance_message')
    return res.status(503).json({
      mode: 'maintenance',
      message: message || 'The site is currently under maintenance.',
    })
  } catch (err) {
    return next(err)
  }
}

module.exports = siteMode
