/**
 * SLA policy management routes — ticket-sla-escalation (P063).
 * Canonical mount: /api/settings/sla.
 * Compatibility alias: /api/support/sla-policies.
 *
 * GET  /               → list all SLA policies for the tenant (OWNER, ADMIN)
 * PATCH /:policyId     → update one policy's targets + notification prefs (OWNER)
 *
 * Business+ gate: sla_enabled must be true on tenant_settings for mutations.
 * The GET returns policies regardless of sla_enabled so the settings UI can
 * show them even when the feature is toggled off.
 */
import { Hono } from 'hono'
import { TenantTier } from '@zync/types'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission, requireTier } from '../../middleware/guards'
import { isOwnerOrAdminRole, isOwnerRole } from '../../lib/system-roles'
import {
  createDb,
  listSlaPolicies,
  getSlaPolicyById,
  getSlaEnabled,
  updateSlaPolicy,
  updateSlaPolicySchema,
} from '@zync/db/queries'

const patchSlaPolicySchema = updateSlaPolicySchema

export const slaPolicyRoutes = new Hono<AppEnv>()

slaPolicyRoutes.use('*', authMiddleware)
slaPolicyRoutes.use('*', requireTier(TenantTier.BUSINESS))

// ── GET /api/support/sla-policies ────────────────────────────────────────────

slaPolicyRoutes.get('/', requirePermission('settings:read'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  if (!isOwnerOrAdminRole(session.role)) {
    return c.json({ error: 'Forbidden — OWNER or ADMIN only' }, 403)
  }

  const db = createDb(c.env)
  const [policies, slaEnabled] = await Promise.all([
    listSlaPolicies(db, session.tid),
    getSlaEnabled(db, session.tid),
  ])

  return c.json({ policies, sla_enabled: slaEnabled }, 200)
})

// ── PATCH /api/support/sla-policies/:policyId ────────────────────────────────

slaPolicyRoutes.patch('/:policyId', requirePermission('settings:write'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  if (!isOwnerRole(session.role)) {
    return c.json({ error: 'Forbidden — OWNER only' }, 403)
  }

  const { policyId } = c.req.param()
  if (!policyId) {
    return c.json({ error: 'Missing policyId' }, 400)
  }

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

  const db = createDb(c.env)

  // Verify policy belongs to tenant before updating
  const existing = await getSlaPolicyById(db, session.tid, policyId)
  if (!existing) {
    return c.json({ error: 'SLA policy not found' }, 404)
  }

  const updated = await updateSlaPolicy(db, session.tid, policyId, parsed.data)

  return c.json({ policy: updated }, 200)
})
