/**
 * Workflow Engine Types
 * TypeScript definitions for the ticket triage workflow engine
 */

// ============================================================================
// Enums & Constants
// ============================================================================

export type RuleType =
  | 'branch_routing'
  | 'ticket_type'
  | 'issue_classification'
  | 'priority'
  | 'queue_routing';

export type MatchField =
  | 'title'
  | 'description'
  | 'title_or_description'
  | 'ticket_category'
  | 'policy_name'
  | 'device_name'
  | 'creator_resource_id'
  | 'priority'
  | 'ticket_type'
  | 'person_id'
  | 'company_id';

export type MatchOperator =
  | 'contains'
  | 'starts_with'
  | 'regex'
  | 'equals'
  | 'in'
  | 'not_in';

export type ConditionOperator =
  | 'equals'
  | 'not_equals'
  | 'in'
  | 'not_in'
  | 'contains'
  | 'not_contains'
  | 'regex'
  | 'gt'
  | 'lt'
  | 'is_null'
  | 'is_not_null';

export type ConfidenceLevel = 'high' | 'medium' | 'low';

export type Branch = 'service_desk' | 'noc' | 'soc';

export type ClassificationMethod = 'robotic' | 'ai' | 'hybrid';

export type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped';

export type StepMethod = 'robotic' | 'ai' | 'skipped';

export type ActionType =
  | 'set_field'
  | 'classify'
  | 'ai_enhance'
  | 'create_note'
  | 'update_autotask'
  | 'delay'
  | 'skip';

export type PromptPurpose =
  | 'title_cleanup'
  | 'description_rewrite'
  | 'ambiguous_classification'
  | 'troubleshooting_steps'
  | 'noc_format'
  | 'soc_analysis';

export type TriggerEvent = 'ticket.created' | 'ticket.updated';

export type StepName =
  | 'filter'
  | 'branch_routing'
  | 'ticket_type'
  | 'issue_classification'
  | 'priority'
  | 'queue_routing'
  | 'validation'
  | 'ai_title'
  | 'ai_description'
  | 'ai_classification'
  | 'ai_troubleshooting'
  | 'autotask_update'
  | 'create_note';

// ============================================================================
// Database Row Types
// ============================================================================

export interface ClassificationRule {
  id: number;
  name: string;
  description: string | null;
  rule_type: RuleType;
  sort_order: number;
  is_active: boolean;
  match_field: MatchField;
  match_operator: MatchOperator;
  match_value: any; // JSONB: string | string[] | regex pattern
  match_case_sensitive: boolean;
  result_field: string;
  result_value: any; // JSONB
  result_field_2: string | null;
  result_value_2: any | null;
  confidence: ConfidenceLevel;
  stop_on_match: boolean;
  created_at: Date;
  updated_at: Date;
}

export interface WorkflowRule {
  id: number;
  name: string;
  description: string | null;
  is_active: boolean;
  sort_order: number;
  trigger_event: TriggerEvent;
  trigger_entity: string;
  stop_processing: boolean;
  created_at: Date;
  updated_at: Date;
}

export interface WorkflowCondition {
  id: number;
  rule_id: number;
  condition_group: number;
  field: string;
  operator: ConditionOperator;
  value: any; // JSONB
  created_at: Date;
}

export interface WorkflowAction {
  id: number;
  rule_id: number;
  sort_order: number;
  action_type: ActionType;
  config: Record<string, any>;
  created_at: Date;
}

export interface AiPromptTemplate {
  id: number;
  name: string;
  purpose: PromptPurpose;
  system_prompt: string;
  user_prompt_template: string;
  provider: string;
  model: string;
  temperature: number;
  max_tokens: number;
  is_active: boolean;
  version: number;
  created_at: Date;
  updated_at: Date;
}

export interface WorkflowExecution {
  id: number;
  trigger_event: string;
  entity_type: string;
  entity_id: number;
  ticket_number: string | null;
  status: ExecutionStatus;
  classification_method: ClassificationMethod | null;
  branch: Branch | null;
  started_at: Date;
  completed_at: Date | null;
  duration_ms: number | null;
  error_message: string | null;
  created_at: Date;
}

export interface WorkflowExecutionStep {
  id: number;
  execution_id: number;
  step_name: StepName;
  step_order: number;
  status: ExecutionStatus;
  method: StepMethod | null;
  input_data: Record<string, any> | null;
  output_data: Record<string, any> | null;
  field_changes: Record<string, { before: any; after: any }> | null;
  classification_rule_id: number | null;
  confidence: ConfidenceLevel | null;
  ai_request: Record<string, any> | null;
  ai_response: string | null;
  attempt_number: number;
  error_message: string | null;
  duration_ms: number | null;
  started_at: Date | null;
  completed_at: Date | null;
}

export interface WorkflowSetting {
  key: string;
  value: any; // JSONB
  description: string | null;
  updated_at: Date;
}

// ============================================================================
// Runtime Types (used during processing)
// ============================================================================

/** Ticket data as consumed by the workflow engine */
export interface TicketData {
  id: number;
  ticket_number: string | null;
  title: string;
  description: string | null;
  ticket_category: number | null;
  ticket_type: number | null;
  priority: number | null;
  queue_id: number | null;
  issue_type: number | null;
  sub_issue_type: number | null;
  company_id: number;
  contact_id: number | null;
  assigned_resource_id: number | null;
  creator_resource_id: number | null;
  person_id: number | null;
  status: number | null;
  source: number | null;
  // Computed/extracted fields for classification
  policy_name?: string | null;
  device_name?: string | null;
}

/** Result from a single classification step */
export interface ClassificationStepResult {
  field: string;
  value: any;
  field_2?: string;
  value_2?: any;
  confidence: ConfidenceLevel;
  matched_rule_id: number | null;
  matched_rule_name: string | null;
  method: StepMethod;
}

/** Full classification result from robotic classifier */
export interface ClassificationResult {
  branch: ClassificationStepResult | null;
  ticket_type: ClassificationStepResult | null;
  issue_classification: ClassificationStepResult | null;
  priority: ClassificationStepResult | null;
  queue: ClassificationStepResult | null;
  overall_confidence: ConfidenceLevel;
  needs_ai: boolean;
  ai_reasons: string[];
}

/** Validation result */
export interface ValidationResult {
  is_valid: boolean;
  errors: ValidationError[];
}

export interface ValidationError {
  field: string;
  message: string;
  value: any;
}

/** AI enhancement result */
export interface AiEnhancementResult {
  title?: string;
  description?: string;
  classification?: {
    issue_type?: number;
    sub_issue_type?: number;
    ticket_type?: number;
    priority?: number;
  };
  troubleshooting_steps?: string;
  method: 'ai';
}

/** Field changes to write back to Autotask */
export interface FieldChanges {
  [field: string]: {
    before: any;
    after: any;
  };
}

/** Full execution result */
export interface ExecutionResult {
  execution_id: number;
  status: ExecutionStatus;
  classification_method: ClassificationMethod;
  branch: Branch;
  field_changes: FieldChanges;
  steps: ExecutionStepSummary[];
  duration_ms: number;
  error?: string;
}

export interface ExecutionStepSummary {
  step_name: StepName;
  status: ExecutionStatus;
  method: StepMethod;
  confidence?: ConfidenceLevel;
  matched_rule?: string;
  duration_ms: number;
}

/** Workflow event that triggers processing */
export interface WorkflowEvent {
  trigger_event: TriggerEvent;
  entity_type: string;
  entity_id: number;
  ticket_number?: string;
  ticket_data?: TicketData;
}

/** Workflow settings loaded into memory */
export interface WorkflowSettings {
  workflow_engine_enabled: boolean;
  default_ai_provider: 'openai' | 'anthropic';
  openai_api_key: string;
  openai_model: string;
  anthropic_api_key: string;
  anthropic_model: string;
  ai_for_title_cleanup: boolean;
  ai_for_description_rewrite: boolean;
  ai_for_ambiguous_classification: boolean;
  ai_for_troubleshooting: boolean;
  autotask_update_delay_ms: number;
  max_ai_retries: number;
  classification_confidence_threshold: ConfidenceLevel;
  log_retention_days: number;
}

// ============================================================================
// API Types (request/response shapes for API routes)
// ============================================================================

export interface ClassificationRuleInput {
  name: string;
  description?: string;
  rule_type: RuleType;
  sort_order?: number;
  is_active?: boolean;
  match_field: MatchField;
  match_operator: MatchOperator;
  match_value: any;
  match_case_sensitive?: boolean;
  result_field: string;
  result_value: any;
  result_field_2?: string;
  result_value_2?: any;
  confidence?: ConfidenceLevel;
  stop_on_match?: boolean;
}

export interface WorkflowRuleInput {
  name: string;
  description?: string;
  is_active?: boolean;
  sort_order?: number;
  trigger_event: TriggerEvent;
  trigger_entity?: string;
  stop_processing?: boolean;
  conditions: WorkflowConditionInput[];
  actions: WorkflowActionInput[];
}

export interface WorkflowConditionInput {
  condition_group?: number;
  field: string;
  operator: ConditionOperator;
  value: any;
}

export interface WorkflowActionInput {
  sort_order?: number;
  action_type: ActionType;
  config?: Record<string, any>;
}

export interface AiPromptTemplateInput {
  name: string;
  purpose: PromptPurpose;
  system_prompt: string;
  user_prompt_template: string;
  provider?: string;
  model?: string;
  temperature?: number;
  max_tokens?: number;
  is_active?: boolean;
}

export interface WorkflowTestRequest {
  ticket_id: number;
  dry_run?: boolean; // default true
}

export interface WorkflowTestResult {
  ticket: TicketData;
  classification: ClassificationResult;
  validation: ValidationResult;
  proposed_changes: FieldChanges;
  execution_steps: ExecutionStepSummary[];
}

/** Workflow rule with its conditions and actions loaded */
export interface WorkflowRuleWithDetails extends WorkflowRule {
  conditions: WorkflowCondition[];
  actions: WorkflowAction[];
}

/** Execution with its steps loaded */
export interface WorkflowExecutionWithSteps extends WorkflowExecution {
  steps: WorkflowExecutionStep[];
}
