/**
 * Inventory settings routes.
 * Mounted at /api/settings/inventory.
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission } from '../../middleware/guards'
import { getInventorySettings, updateInventorySettings } from '@zync/db/queries'

const patchInventorySettingsSchema = z
  .object({
    inventory_method: z.string().min(1).max(64).optional(),
    allow_negative: z.boolean().optional(),
  })
  .strict()

export const inventorySettingsRoute = new Hono<AppEnv>()

inventorySettingsRoute.use('*', authMiddleware)

inventorySettingsRoute.get('/', requirePermission('inventory:read'), 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')
  const settings = await getInventorySettings(db, session.tid)
  return c.json(settings, 200)
})

inventorySettingsRoute.patch('/', requirePermission('inventory:write'), 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 = patchInventorySettingsSchema.safeParse(body)
  if (!parsed.success) {
    return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)
  }

  const db = c.get('db')
  const updated = await updateInventorySettings(db, session.tid, parsed.data)
  return c.json(updated, 200)
})
