/**
 * Staff portal session management — customers module (Task 10).
 *
 * POST /api/customers/:id/portal-users/:uid/revoke-sessions
 *   Revoke all active portal_sessions for the portal user's customer.
 */
import { Hono } from 'hono'
import { revokeAllPortalSessions } from '@zync/auth'
import { getPortalUserById } from '@zync/db/queries'
import type { AppEnv } from '../../types'
import { requirePermission } from '../../middleware/guards'

export const portalSessionsRoute = new Hono<AppEnv>()

portalSessionsRoute.post(
  '/:id/portal-users/:uid/revoke-sessions',
  requirePermission('users:invite'),
  async (c) => {
    const session = c.get('session')
    if (!session || session.type !== 'user' || !session.tid) {
      return c.json({ error: 'Unauthorized' }, 401)
    }

    const customerId = c.req.param('id')
    const portalUserId = c.req.param('uid')
    const db = c.get('db')

    const portalUser = await getPortalUserById(db, session.tid, portalUserId)
    if (!portalUser || portalUser.customerId !== customerId) {
      return c.json({ error: 'Not found' }, 404)
    }

    await revokeAllPortalSessions(db, session.tid, portalUser.customerId)

    return c.body(null, 204)
  },
)
