import { ensureUserNotificationPreference } from '../../lib/notifications/preferences.js'
import { prisma } from '../../lib/prisma.js'

export async function registerUserNotificationRoutes(fastify) {
  fastify.get('/api/me/notifications/settings', { preHandler: [fastify.authenticate] }, async (request) => {
    const userId = request.user.sub
    const prefs = await ensureUserNotificationPreference(userId)
    return { settings: prefs }
  })

  fastify.put('/api/me/notifications/settings', { preHandler: [fastify.authenticate] }, async (request) => {
    const userId = request.user.sub
    const body = request.body || {}

    const data = {}
    if ('globalEnabled' in body) data.globalEnabled = Boolean(body.globalEnabled)
    if ('orderCreated' in body) data.orderCreated = Boolean(body.orderCreated)
    if ('orderStatusChanged' in body) data.orderStatusChanged = Boolean(body.orderStatusChanged)
    if ('orderMessageReceived' in body) data.orderMessageReceived = Boolean(body.orderMessageReceived)
    if ('paymentStatusChanged' in body) data.paymentStatusChanged = Boolean(body.paymentStatusChanged)
    if ('deliveryFeeAdjusted' in body) data.deliveryFeeAdjusted = Boolean(body.deliveryFeeAdjusted)

    const prefs = await prisma.notificationPreference.upsert({
      where: { userId },
      create: { userId, ...data },
      update: data,
    })

    return { settings: prefs }
  })
}
