/**
 * Blocked-destructive-operations guard for impersonation sessions —
 * admin-impersonation spec.
 *
 * When a request is made within an impersonation session (`session.impersonation
 * === true`), certain destructive operations are forbidden. This middleware must
 * run AFTER authMiddleware (so `session` is populated) and BEFORE the handler.
 *
 * Blocked routes (per spec):
 *   DELETE /api/zync-subscription            — cancel/delete tenant subscription
 *   POST   /api/zync-subscription/checkout   — start checkout / change billing
 *   PATCH  /api/billing/email                — update billing contact email
 *   PATCH  /api/settings/payment-gateway     — store payment-gateway credentials
 *   Any tenant-account deletion route (e.g. DELETE /api/settings/account)
 *   Any /api/settings/billing/payment-method* route (when implemented)
 */
import type { MiddlewareHandler } from 'hono'
import type { AppEnv } from '../types'
import type { SessionPayload } from '@zync/types'

export function blockDuringImpersonation(): MiddlewareHandler<AppEnv> {
  return async (c, next) => {
    const session = c.get('session') as SessionPayload | undefined
    if (session?.impersonation === true) {
      return c.json(
        { error: 'Impersonation sessions cannot perform this action' },
        403,
      )
    }
    return next()
  }
}
