/**
 * Platform Email Tool Types
 *
 * Zod schemas and inferred types for platform email sending.
 * Supports three targeting modes: explicit userIds, role-based, or broadcast.
 */

import { z } from 'zod'
import { EmailSchema } from '../../../../../platform/utils/validation'

// =============================================================================
// INPUT SCHEMA
// =============================================================================

/**
 * Input schema for sending platform emails
 *
 * Targeting modes (exactly one required):
 * - userIds: Explicit list of user IDs to email
 * - targetRole: Role to target (e.g., "admin")
 * - targetAll: Send to all org members
 *
 * Content (at least one required):
 * - html: HTML email body
 * - text: Plain text email body
 */
export const SendPlatformEmailInputSchema = z
  .object({
    // Targeting (exactly one required)
    userIds: z.array(z.string().uuid()).optional().describe('Explicit list of user IDs to email'),
    targetRole: z.string().optional().describe('Role to target (e.g., "admin")'),
    targetAll: z.boolean().optional().describe('Send to all org members'),

    // Content
    subject: z.string().min(1).max(200),
    html: z.string().optional(),
    text: z.string().optional(),

    // Optional
    replyTo: EmailSchema.optional(),
    tags: z
      .array(
        z.object({
          name: z.string(),
          value: z.string()
        })
      )
      .optional()
  })
  .refine(
    (data) => {
      const modes = [data.userIds?.length, data.targetRole, data.targetAll].filter(Boolean)
      return modes.length === 1
    },
    { message: 'Exactly one targeting mode required: userIds, targetRole, or targetAll' }
  )
  .refine((data) => data.html || data.text, { message: 'Must provide either html or text body' })

export type SendPlatformEmailInput = z.infer<typeof SendPlatformEmailInputSchema>

// =============================================================================
// OUTPUT SCHEMA
// =============================================================================

/**
 * Output schema for platform email send result
 * Follows partial success pattern (similar to BatchProcessResult)
 */
export const SendPlatformEmailOutputSchema = z.object({
  sent: z.number().int(),
  failed: z.number().int(),
  errors: z
    .array(
      z.object({
        userId: z.string().uuid(),
        email: EmailSchema,
        error: z.string()
      })
    )
    .optional()
})

export type SendPlatformEmailOutput = z.infer<typeof SendPlatformEmailOutputSchema>

// =============================================================================
// TOOL CONFIG
// =============================================================================

/**
 * Configuration for creating a platform email tool
 */
export interface PlatformEmailToolConfig {
  /** Unique name for the tool */
  name: string
  /** Description of what the tool does (shown to LLM) */
  description: string
}
