/**
 * Bad-debt settings — bad-debt-writeoff (wave-12).
 * Mounted at /api/settings/bad-debt.
 *
 * GET  / → { bad_debt_threshold_days }   (OWNER or ADMIN)
 * PATCH / → update bad_debt_threshold_days  (OWNER only)
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { createDb, getBadDebtSettings, updateBadDebtSettings } from '@zync/db/queries'

const patchSchema = z.object({
  bad_debt_threshold_days: z.number().int().min(1).max(3650),
})

export const badDebtSettingsRoute = new Hono<AppEnv>()

badDebtSettingsRoute.use('*', authMiddleware)

// GET /api/settings/bad-debt
badDebtSettingsRoute.get('/', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  const role = session.role ?? ''
  if (!['OWNER', 'ADMIN'].includes(role)) {
    return c.json({ error: 'Forbidden' }, 403)
  }

  const db = createDb(c.env)
  const result = await getBadDebtSettings(db, session.tid)
  return c.json(result, 200)
})

// PATCH /api/settings/bad-debt
badDebtSettingsRoute.patch('/', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  const role = session.role ?? ''
  if (role !== 'OWNER') {
    return c.json({ error: 'Forbidden — OWNER only' }, 403)
  }

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

  const db = createDb(c.env)
  const result = await updateBadDebtSettings(db, session.tid, parsed.data.bad_debt_threshold_days)
  return c.json(result, 200)
})
