/**
 * Customer settings routes — settings-customers (wave 11).
 * Mounted at /api/settings/customers.
 *
 * GET  / → CustomerSettingsDTO (requires customers:read)
 * PATCH / → CustomerSettingsDTO (requires customers:write)
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission } from '../../middleware/guards'
import {
  getCustomerSettings,
  updateCustomerSettings,
} from '@zync/db/queries'

// ── Validation ────────────────────────────────────────────────────────────────

const updateCustomerSettingsSchema = z
  .object({
    customer_default_currency: z.string().min(3).max(3).toUpperCase().optional(),
    customer_auto_invite_portal: z
      .enum(['never', 'on_creation', 'on_first_invoice'])
      .optional(),
  })
  .strict()
  .refine(
    (b) =>
      b.customer_default_currency !== undefined ||
      b.customer_auto_invite_portal !== undefined,
    { message: 'At least one field must be provided' },
  )

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

export const customerSettingsRoute = new Hono<AppEnv>()

customerSettingsRoute.use('*', authMiddleware)

// ── GET /api/settings/customers ───────────────────────────────────────────────

customerSettingsRoute.get('/', requirePermission('customers: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 dto = await getCustomerSettings(db, session.tid)
  return c.json(dto, 200)
})

// ── PATCH /api/settings/customers ─────────────────────────────────────────────

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

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