/**
 * PATCH /api/tenant/settings — system-i18n.
 *
 * Updates tenant-level settings. Currently supports:
 * - `country_code`: ISO 3166-1 alpha-2 (must be in supported set).
 *
 * Guarded by `settings:manage` permission (tenant-admin operation).
 * The DB CHECK constraint on tenants.country_code enforces the supported set
 * server-side; Zod provides early validation.
 *
 * Security:
 * - Protected by authMiddleware + requirePermission('settings:manage').
 * - Zod schema validates all accepted fields before touching the DB.
 */
import { Hono } from 'hono'
import { z } from 'zod'
import { createDb, setTenantCountryCode, setTenantForceShell } from '@zync/db/queries'
import type { AppEnv } from '../types'
import { authMiddleware } from '../middleware/auth'
import { requirePermission } from '../middleware/guards'

const patchTenantSettingsSchema = z.object({
  country_code: z.enum(['IL']).optional(),
  force_shell: z.enum(['classic', 'os']).nullable().optional(),
})

export const tenantSettingsRoute = new Hono<AppEnv>()

tenantSettingsRoute.use('*', authMiddleware)

tenantSettingsRoute.patch(
  '/',
  requirePermission('settings:write'),
  async (c) => {
    const session = c.get('session')
    if (!session || session.type !== 'user' || !session.tid) {
      return c.json({ error: 'Unauthorized' }, 401)
    }

    const parsed = patchTenantSettingsSchema.safeParse(await c.req.json())
    if (!parsed.success) {
      return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
    }

    const db = createDb(c.env)

    if (parsed.data.country_code !== undefined) {
      await setTenantCountryCode(db, session.tid, parsed.data.country_code)
    }
    if (parsed.data.force_shell !== undefined) await setTenantForceShell(db, session.tid, session.sub, parsed.data.force_shell)

    return c.json({ country_code: parsed.data.country_code ?? null, force_shell: parsed.data.force_shell ?? null }, 200)
  },
)
