/**
 * Notification preferences routes — notification-preferences (spec 97).
 * Mounted at /api/notifications/preferences.
 *
 * GET  / → { email, inApp, digest }
 * PATCH / → update notification preferences
 *
 * Guarded by authMiddleware (user session required).
 * PATCH writes an audit log row in the same transaction (via query helper).
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import {
  createDb,
  getNotificationPreferences,
  updateNotificationPreferences,
} from '@zync/db/queries'

// ── Zod schemas ───────────────────────────────────────────────────────────────

const NotificationEventPrefsSchema = z.object({
  invoicePaid: z.boolean(),
  invoiceOverdue: z.boolean(),
  newLead: z.boolean(),
  projectMilestone: z.boolean(),
  ticketReply: z.boolean(),
})

const patchNotificationPreferencesSchema = z.object({
  email: NotificationEventPrefsSchema.optional(),
  inApp: NotificationEventPrefsSchema.optional(),
  digest: z.enum(['none', 'daily', 'weekly']).optional(),
})

// ── Router ────────────────────────────────────────────────────────────────────

export const notificationPreferencesRoute = new Hono<AppEnv>()

notificationPreferencesRoute.use('*', authMiddleware)

// GET /api/notifications/preferences
notificationPreferencesRoute.get('/preferences', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const db = c.get('db') ?? createDb(c.env)
  const prefs = await getNotificationPreferences(db, session.tid, session.sub)

  return c.json(prefs, 200)
})

// PATCH /api/notifications/preferences
notificationPreferencesRoute.patch('/preferences', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const body = await c.req.json().catch(() => null)
  const parsed = patchNotificationPreferencesSchema.safeParse(body)
  if (!parsed.success) {
    return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)
  }

  const db = c.get('db') ?? createDb(c.env)

  // Merge patch onto existing prefs
  const existing = await getNotificationPreferences(db, session.tid, session.sub)
  const updated = {
    email: parsed.data.email ?? existing.email,
    inApp: parsed.data.inApp ?? existing.inApp,
    digest: parsed.data.digest ?? existing.digest,
  }

  const ip = c.req.header('CF-Connecting-IP') ?? null
  const requestId = c.req.header('X-Request-Id') ?? null

  await updateNotificationPreferences(db, session.tid, session.sub, updated, {
    actorIp: ip,
    requestId,
  })

  return c.json(updated, 200)
})
