const express = require('express')
const { z } = require('zod')
const {
  listCommentNotifications,
  countUnreadCommentNotifications,
  markCommentNotificationsRead,
} = require('../db')
const { requireAuth } = require('../middleware/auth')

const router = express.Router()

router.get('/inbox', requireAuth, async (req, res) => {
  const schema = z.object({
    unreadOnly: z
      .union([z.literal('1'), z.literal('0'), z.literal('true'), z.literal('false')])
      .optional()
      .default('0'),
  })
  const parsed = schema.safeParse(req.query)
  if (!parsed.success) return res.status(400).json({ error: 'bad_request' })

  const unreadOnly = ['1', 'true'].includes(parsed.data.unreadOnly)
  const notifications = await listCommentNotifications(req.session.userId, { unreadOnly })
  res.json({ notifications })
})

router.get('/inbox/unread-count', requireAuth, async (req, res) => {
  const unreadCount = await countUnreadCommentNotifications(req.session.userId)
  res.json({ unreadCount })
})

router.post('/inbox/read', requireAuth, async (req, res) => {
  const schema = z.object({
    all: z.boolean().optional().default(false),
    notificationIds: z.array(z.string().min(1).max(64)).max(100).optional().default([]),
  })
  const parsed = schema.safeParse(req.body)
  if (!parsed.success) return res.status(400).json({ error: 'bad_request' })

  await markCommentNotificationsRead(req.session.userId, {
    all: parsed.data.all,
    notificationIds: parsed.data.notificationIds,
  })

  const unreadCount = await countUnreadCommentNotifications(req.session.userId)
  res.json({ ok: true, unreadCount })
})

module.exports = router
