/**
 * Automation Service Types
 *
 * Type definitions for workflow execution services.
 */

import type { IAutomationInstance, IWorkflowNode, INodeConfig } from '../../models/AutomationWorkflow';

// ============================================
// NODE HANDLER TYPES
// ============================================

/**
 * Result of executing a node
 */
export interface NodeExecutionResult {
  success: boolean;
  output?: Record<string, any>;
  error?: string;
  // For condition nodes, which branch to take
  branch?: 'true' | 'false';
  // For split nodes, which path was selected
  selectedPath?: string;
  // For delay nodes, when to resume
  resumeAt?: Date;
}

/**
 * Handler for a specific node type
 */
export interface NodeHandler {
  // Node type identifier
  type: string;

  // Node category
  category: 'trigger' | 'action' | 'flow';

  // Validate node configuration before execution
  validate?(config: INodeConfig): Promise<{ valid: boolean; errors: string[] }>;

  // Execute the node (for actions)
  execute?(
    instance: IAutomationInstance,
    node: IWorkflowNode,
    context: ExecutionContext
  ): Promise<NodeExecutionResult>;

  // Get available output branches (for flow control nodes)
  getOutputs?(config: INodeConfig): string[];

  // Display metadata
  getMetadata(): NodeMetadata;
}

/**
 * Node display metadata
 */
export interface NodeMetadata {
  label: string;
  description: string;
  icon: string;
  category: string;
}

// ============================================
// EXECUTION CONTEXT TYPES
// ============================================

/**
 * Context passed to node handlers during execution
 */
export interface ExecutionContext {
  // Company ID
  companyId: string;

  // Workflow ID
  workflowId: string;

  // Instance ID
  instanceId: string;

  // Contact data
  contact: ContactData;

  // Instance variables (mutable during execution)
  variables: Record<string, any>;

  // Workflow settings
  settings: WorkflowSettings;

  // Test mode flag
  isTestMode: boolean;
}

/**
 * Contact data available during execution
 */
export interface ContactData {
  id: string;
  email?: string;
  phone?: string;
  firstName?: string;
  lastName?: string;
  tags?: string[];
  customFields?: Record<string, any>;
  lists?: string[];
  segments?: string[];
  [key: string]: any;
}

/**
 * Workflow settings
 */
export interface WorkflowSettings {
  allowReentry: boolean;
  reentryCooldown?: number;
  timezone: string;
  notifyOnCompletion: boolean;
  notifyOnError: boolean;
  notificationEmails?: string[];
  testMode: boolean;
  testContactId?: string;
}

// ============================================
// TRIGGER TYPES
// ============================================

/**
 * Event that can trigger workflows
 */
export interface TriggerEvent {
  // Event type (maps to trigger types)
  type: string;

  // Company ID
  companyId: string;

  // Contact data
  contact: ContactData;

  // Event-specific data
  data: Record<string, any>;

  // When the event occurred
  timestamp: Date;
}

/**
 * Matched workflow for a trigger event
 */
export interface TriggerMatch {
  workflowId: string;
  triggerId: string;
  instanceId: string;
}

// ============================================
// INSTANCE TYPES
// ============================================

/**
 * Instance creation options
 */
export interface CreateInstanceOptions {
  companyId: string;
  workflowId: string;
  contactId: string;
  variables?: Record<string, any>;
  testMode?: boolean;
}

/**
 * Instance processing result
 */
export interface ProcessResult {
  success: boolean;
  instanceId: string;
  status: 'completed' | 'paused' | 'error' | 'exited';
  currentNodeId?: string;
  error?: string;
}

// ============================================
// DELAY TYPES
// ============================================

/**
 * Scheduled delay entry
 */
export interface ScheduledDelay {
  instanceId: string;
  workflowId: string;
  companyId: string;
  nodeId: string;
  scheduledFor: Date;
  createdAt: Date;
}

// ============================================
// ANALYTICS TYPES
// ============================================

/**
 * Workflow statistics
 */
export interface WorkflowAnalytics {
  workflowId: string;
  totalInstances: number;
  activeInstances: number;
  completedInstances: number;
  exitedInstances: number;
  errorInstances: number;
  completionRate: number;
  averageCompletionTime: number;
  lastTriggeredAt?: Date;
}

/**
 * Node performance metrics
 */
export interface NodePerformance {
  nodeId: string;
  nodeType: string;
  executions: number;
  avgDuration: number;
  errorRate: number;
}

/**
 * Time-series data point
 */
export interface TimeSeriesPoint {
  date: string;
  value: number;
}