import type { Tool, ToolExecutionOptions } from '../types'
import { serviceUnavailable } from '../types'
import type { CreateNotificationParams } from '../../../../operations/notifications/types'
import { getToolServices } from '../registry'
import type { NotificationToolConfig } from './types'

/**
 * Create a notification tool that sends platform notifications to users
 *
 * Notification tools enable agents and workflows to send in-app notifications
 * to users. Notifications appear in the user's notification feed and can include
 * action URLs for navigation.
 *
 * @param config - Configuration for the notification tool
 * @returns Tool that creates notifications
 *
 * @example
 * const notifyTool = createNotificationTool({
 *   name: 'notify_user',
 *   description: 'Send notification to user about task completion',
 *   inputSchema: z.object({
 *     userId: z.string(),
 *     title: z.string(),
 *     message: z.string(),
 *     category: z.enum(['info', 'success', 'warning', 'error']),
 *     actionUrl: z.string().optional()
 *   }),
 *   outputSchema: z.object({ notificationId: z.string() })
 * })
 */
export function createNotificationTool(config: NotificationToolConfig): Tool {
  return {
    name: config.name,
    description: config.description,
    inputSchema: config.inputSchema,
    outputSchema: config.outputSchema,

    async execute(options: ToolExecutionOptions): Promise<unknown> {
      // ExecutionContext is required for platform tools
      if (!options.executionContext) {
        throw serviceUnavailable('ExecutionContext', {
          tool: config.name,
          reason: 'organizationId required for multi-tenant isolation'
        })
      }

      // Get notifications service from global registry
      const { notificationsService } = getToolServices()
      if (!notificationsService) {
        throw serviceUnavailable('NotificationsService', {
          message: 'Ensure toolServicesRegistry.initialize() was called in apps/api/src/main.ts',
          tool: config.name
        })
      }

      // Build notification parameters — input is validated against inputSchema before execution
      const inputData = options.input as {
        userId: string
        category: string
        title: string
        message: string
        actionUrl?: string
      }

      const params: CreateNotificationParams = {
        userId: config.userId ?? inputData.userId,
        organizationId: options.executionContext.organizationId,
        category: config.category ?? inputData.category,
        title: inputData.title,
        message: inputData.message,
        actionUrl: inputData.actionUrl
      }

      // Create notification
      const notification = await notificationsService.create(params)

      // Return notification ID for tracking
      return { notificationId: notification.id }
    }
  }
}
