import * as plugins from '../../plugins.js';
import type { AdminHandler } from '../handlers/admin.handler.js';
import * as interfaces from '../../../ts_interfaces/index.js';

/**
 * Helper function to use identity guards in handlers
 * 
 * @example
 * // In a handler:
 * await passGuards(toolsArg, this.opsServerRef.adminHandler.validIdentityGuard, dataArg);
 */
export async function passGuards<T extends { identity?: any }>(
  toolsArg: any,
  guard: plugins.smartguard.Guard<T>,
  dataArg: T
): Promise<void> {
  const result = await guard.exec(dataArg);
  if (!result) {
    const failedHint = await guard.getFailedHint(dataArg);
    throw new plugins.typedrequest.TypedResponseError(failedHint || 'Guard check failed');
  }
}

/**
 * Helper to check admin identity in handlers and middleware.
 * Accepts both optional and required identity for flexibility.
 */
export async function requireAdminIdentity(
  adminHandler: AdminHandler,
  dataArg: { identity?: interfaces.data.IIdentity }
): Promise<void> {
  if (!dataArg.identity) {
    throw new plugins.typedrequest.TypedResponseError('No identity provided');
  }

  const passed = await adminHandler.adminIdentityGuard.exec({ identity: dataArg.identity });
  if (!passed) {
    throw new plugins.typedrequest.TypedResponseError('Admin access required');
  }
}

/**
 * Helper to check valid identity in handlers and middleware.
 * Accepts both optional and required identity for flexibility.
 */
export async function requireValidIdentity(
  adminHandler: AdminHandler,
  dataArg: { identity?: interfaces.data.IIdentity }
): Promise<void> {
  if (!dataArg.identity) {
    throw new plugins.typedrequest.TypedResponseError('No identity provided');
  }

  const passed = await adminHandler.validIdentityGuard.exec({ identity: dataArg.identity });
  if (!passed) {
    throw new plugins.typedrequest.TypedResponseError('Valid identity required');
  }
}