import { requireAuth } from '../auth.js'
import { getConfig } from '../db.js'
import { getBookingsData, todayStr, offsetDate } from '../lib/newbook.js'

export async function bookingRoutes(app) {
  app.addHook('preHandler', requireAuth)

  app.get('/api/bookings', async (req, reply) => {
    const today = todayStr()

    let weekStart = req.query.week_start || today
    if (!/^\d{4}-\d{2}-\d{2}$/.test(weekStart)) weekStart = today

    let lastViewed = req.query.last_viewed || offsetDate(today, -1)
    if (!/^\d{4}-\d{2}-\d{2}$/.test(lastViewed)) lastViewed = offsetDate(today, -1)

    const force = req.query.force_refresh === '1'

    try {
      return await getBookingsData(weekStart, lastViewed, force, getConfig)
    } catch (err) {
      app.log.error(err)
      return reply.status(500).send({ error: err.message })
    }
  })
}
