const { Router } = require('express')
const mongoose = require('mongoose')

const { getAnswer } = require('../../utils/common')
const { CigaretteModel } = require('./model/cigarette')
const { authMiddleware } = require('./middleware/auth')

const router = Router()

// Все эндпоинты ниже требуют авторизации
router.use(authMiddleware)

// Логирование одной сигареты
router.post('/', async (req, res, next) => {
  try {
    const { smokedAt, note } = req.body || {}
    const user = req.user

    let date
    if (smokedAt) {
      const parsed = new Date(smokedAt)
      if (Number.isNaN(parsed.getTime())) {
        throw new Error('Некорректный формат даты smokedAt')
      }
      date = parsed
    } else {
      date = new Date()
    }

    const item = await CigaretteModel.create({
      userId: new mongoose.Types.ObjectId(user.id),
      smokedAt: date,
      note,
    })

    res.json(getAnswer(null, item))
  } catch (err) {
    next(err)
  }
})

// Получение списка сигарет пользователя (для отладки и таблиц)
router.get('/', async (req, res, next) => {
  try {
    const user = req.user
    const { from, to } = req.query

    const filter = { userId: new mongoose.Types.ObjectId(user.id) }

    if (from || to) {
      filter.smokedAt = {}
      if (from) {
        const fromDate = new Date(from)
        if (!Number.isNaN(fromDate.getTime())) {
          filter.smokedAt.$gte = fromDate
        }
      }
      if (to) {
        const toDate = new Date(to)
        if (!Number.isNaN(toDate.getTime())) {
          filter.smokedAt.$lte = toDate
        }
      }
    }

    const items = await CigaretteModel.find(filter).sort({ smokedAt: 1 })

    res.json(getAnswer(null, items))
  } catch (err) {
    next(err)
  }
})

module.exports = router


