/**
 * Platform Email Tool
 *
 * Factory function for creating a platform email tool that sends
 * transactional emails from notifications@elevasis.io using platform Resend credentials.
 *
 * Usage:
 * ```typescript
 * const emailTool = createPlatformEmailTool({
 *   name: 'send_platform_email',
 *   description: 'Send platform notification emails to users'
 * })
 * ```
 */

import type { Tool, ToolExecutionOptions } from '../../types'
import { serviceUnavailable } from '../../types'
import { getToolServices } from '../../registry'
import type { SendPlatformEmailParams } from '../../registry'
import {
  SendPlatformEmailInputSchema,
  SendPlatformEmailOutputSchema,
  type SendPlatformEmailInput,
  type SendPlatformEmailOutput,
  type PlatformEmailToolConfig
} from './types'

/**
 * Create a platform email tool that sends emails to targeted users
 *
 * Platform email tools enable agents and workflows to send transactional emails
 * from the platform email address (notifications@elevasis.io). Emails can target
 * specific users, users with a role, or all organization members.
 *
 * @param config - Configuration for the email tool
 * @returns Tool that sends platform emails
 *
 * @example
 * const emailTool = createPlatformEmailTool({
 *   name: 'notify_admins',
 *   description: 'Send email notification to all admin users'
 * })
 *
 * // Execute with explicit user targeting
 * await emailTool.execute({
 *   input: {
 *     userIds: ['user-id-1', 'user-id-2'],
 *     subject: 'Workflow completed',
 *     html: '<p>Your workflow has completed successfully.</p>'
 *   },
 *   executionContext: context
 * })
 *
 * // Execute with role-based targeting
 * await emailTool.execute({
 *   input: {
 *     targetRole: 'admin',
 *     subject: 'System alert',
 *     text: 'A critical error occurred.'
 *   },
 *   executionContext: context
 * })
 */
export function createPlatformEmailTool(config: PlatformEmailToolConfig): Tool {
  return {
    name: config.name,
    description: config.description,
    inputSchema: SendPlatformEmailInputSchema,
    outputSchema: SendPlatformEmailOutputSchema,

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

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

      // Build email parameters from input + context
      const inputData = options.input as SendPlatformEmailInput

      const params: SendPlatformEmailParams = {
        organizationId: options.executionContext.organizationId,

        // Targeting (exactly one will be set, validated by schema)
        userIds: inputData.userIds,
        targetRole: inputData.targetRole,
        targetAll: inputData.targetAll,

        // Content
        subject: inputData.subject,
        html: inputData.html,
        text: inputData.text,

        // Optional
        replyTo: inputData.replyTo,
        tags: inputData.tags
      }

      // Send email via service
      const result = await emailService.send(params)

      return result
    }
  }
}

// Re-export types for consumers
export {
  SendPlatformEmailInputSchema,
  SendPlatformEmailOutputSchema,
  type SendPlatformEmailInput,
  type SendPlatformEmailOutput,
  type PlatformEmailToolConfig
} from './types'
