/**
 * Shared test fixtures for Sequensy admin frontend tests
 * Extends the mock data from handlers.ts with additional test scenarios
 */
import type { Edge } from '@xyflow/react';
import type { WorkflowReactFlowNode, WorkflowNodeData } from '../../types/reactflow';

// Re-export existing mock data from handlers
export { mockTriggers, mockActions, mockWorkflows, mockIntegrations } from '../mocks/handlers';

// ============================================================================
// React Flow Nodes & Edges
// ============================================================================

export const TRIGGER_NODE_ID = 'node-trigger';
export const ACTION_NODE_ID = 'node-action-1';
export const ACTION_NODE_ID_2 = 'node-action-2';

export function createMockTriggerNode(
  overrides: Partial<WorkflowNodeData> = {},
): WorkflowReactFlowNode {
  return {
    id: TRIGGER_NODE_ID,
    type: 'trigger',
    position: { x: 250, y: 80 },
    data: {
      name: 'User Registration',
      icon: 'UserPlus',
      actionType: 'wordpress/user_registration',
      integration: 'wordpress',
      appName: 'WordPress',
      appService: 'wordpress',
      config: {},
      filters: null,
      status: 'valid',
      stepNumber: 1,
      validationErrors: [],
      ...overrides,
    },
  };
}

export function createMockActionNode(
  id: string = ACTION_NODE_ID,
  overrides: Partial<WorkflowNodeData> = {},
): WorkflowReactFlowNode {
  return {
    id,
    type: 'action',
    position: { x: 250, y: 240 },
    data: {
      name: 'Send Email',
      icon: 'Mail',
      label: 'send_email',
      actionType: 'wordpress/send_email',
      integration: 'wordpress',
      appName: 'WordPress',
      appService: 'wordpress',
      config: {
        to: '{{Trigger.user_email}}',
        subject: 'Welcome!',
        message: 'Thanks for registering!',
      },
      status: 'valid',
      stepNumber: 2,
      validationErrors: [],
      ...overrides,
    },
  };
}

export function createMockPlaceholderNode(
  type: 'trigger' | 'action',
  id?: string,
): WorkflowReactFlowNode {
  const nodeId = id ?? (type === 'trigger' ? TRIGGER_NODE_ID : `node-action-${Date.now()}`);
  return {
    id: nodeId,
    type,
    position: { x: 250, y: type === 'trigger' ? 80 : 240 },
    data: {
      name: type === 'trigger' ? 'Select Trigger' : 'Select Action',
      icon: 'Plus',
      actionType: undefined,
      status: 'placeholder',
      stepNumber: type === 'trigger' ? 1 : 2,
      validationErrors: [],
    },
  };
}

export function createMockEdge(source: string, target: string, id?: string): Edge {
  return {
    id: id ?? `${source}-${target}`,
    source,
    target,
    type: 'smoothstep',
  };
}

/**
 * Complete workflow with trigger and one action
 */
export const mockWorkflowNodes: WorkflowReactFlowNode[] = [
  createMockTriggerNode(),
  createMockActionNode(),
];

export const mockWorkflowEdges: Edge[] = [createMockEdge(TRIGGER_NODE_ID, ACTION_NODE_ID)];

/**
 * Workflow with multiple actions
 */
export const mockMultiActionNodes: WorkflowReactFlowNode[] = [
  createMockTriggerNode(),
  createMockActionNode(ACTION_NODE_ID, { stepNumber: 2 }),
  createMockActionNode(ACTION_NODE_ID_2, {
    name: 'Create Post',
    label: 'create_post',
    actionType: 'wordpress/create_post',
    stepNumber: 3,
    config: {
      post_title: '{{Trigger.user_login}} signed up',
      post_status: 'publish',
    },
  }),
];

export const mockMultiActionEdges: Edge[] = [
  createMockEdge(TRIGGER_NODE_ID, ACTION_NODE_ID),
  createMockEdge(ACTION_NODE_ID, ACTION_NODE_ID_2),
];

// ============================================================================
// Action Schemas (for field testing)
// ============================================================================

export const mockSendEmailSchema = {
  to: {
    type: 'string' as const,
    label: 'To',
    description: 'Recipient email address',
    required: true,
    placeholder: 'email@example.com',
  },
  subject: {
    type: 'string' as const,
    label: 'Subject',
    description: 'Email subject line',
    required: true,
  },
  message: {
    type: 'text' as const,
    label: 'Message',
    description: 'Email body content',
    required: true,
  },
  reply_to: {
    type: 'string' as const,
    label: 'Reply-To',
    description: 'Reply-to address',
    required: false,
  },
};

export const mockCreatePostSchema = {
  post_title: {
    type: 'string' as const,
    label: 'Title',
    description: 'Post title',
    required: true,
  },
  post_content: {
    type: 'text' as const,
    label: 'Content',
    description: 'Post content',
    required: false,
  },
  post_status: {
    type: 'select' as const,
    label: 'Status',
    description: 'Post status',
    required: false,
    options: [
      { value: 'draft', label: 'Draft' },
      { value: 'publish', label: 'Published' },
      { value: 'pending', label: 'Pending Review' },
    ],
  },
  post_type: {
    type: 'select' as const,
    label: 'Post Type',
    description: 'Type of post to create',
    required: true,
    options: [
      { value: 'post', label: 'Post' },
      { value: 'page', label: 'Page' },
    ],
  },
};

export const mockDynamicSelectSchema = {
  list_id: {
    type: 'select' as const,
    label: 'Mailchimp List',
    description: 'Select a mailing list',
    required: true,
    dynamic: true,
    endpoint: '/integrations/mailchimp/lists',
    value_field: 'id',
    label_field: 'name',
  },
  tag_id: {
    type: 'select' as const,
    label: 'Tag',
    description: 'Select a tag',
    required: false,
    dynamic: true,
    endpoint: '/integrations/mailchimp/lists/{list_id}/tags',
    value_field: 'id',
    label_field: 'name',
    depends_on: 'list_id',
  },
};

export const mockConditionalSchema = {
  notification_type: {
    type: 'select' as const,
    label: 'Notification Type',
    required: true,
    options: [
      { value: 'email', label: 'Email' },
      { value: 'slack', label: 'Slack' },
    ],
  },
  email_address: {
    type: 'string' as const,
    label: 'Email Address',
    required: true,
    visible_when: {
      field: 'notification_type',
      operator: 'equals',
      value: 'email',
    },
  },
  slack_channel: {
    type: 'string' as const,
    label: 'Slack Channel',
    required: true,
    visible_when: {
      field: 'notification_type',
      operator: 'equals',
      value: 'slack',
    },
  },
};

export const mockKeyValueSchema = {
  custom_fields: {
    type: 'key_value' as const,
    label: 'Custom Fields',
    description: 'Add custom field mappings',
    required: false,
    available_keys_endpoint: '/integrations/airtable/fields',
    depends_on: 'table_id',
  },
};

export const mockRepeatableSchema = {
  recipients: {
    type: 'repeatable' as const,
    label: 'Recipients',
    description: 'Add multiple recipients',
    required: true,
    fields: {
      email: {
        type: 'string' as const,
        label: 'Email',
        required: true,
      },
      name: {
        type: 'string' as const,
        label: 'Name',
        required: false,
      },
    },
  },
};

// ============================================================================
// Filter Fixtures
// ============================================================================

export const mockFilterGroup = {
  logic: 'AND' as const,
  conditions: [
    {
      field: 'user_email',
      operator: 'contains',
      value: '@company.com',
    },
    {
      field: 'user_role',
      operator: 'equals',
      value: 'subscriber',
    },
  ],
  groups: [],
};

export const mockNestedFilterGroup = {
  logic: 'OR' as const,
  conditions: [],
  groups: [
    {
      logic: 'AND' as const,
      conditions: [
        { field: 'post_status', operator: 'equals', value: 'publish' },
        { field: 'post_type', operator: 'equals', value: 'post' },
      ],
      groups: [],
    },
    {
      logic: 'AND' as const,
      conditions: [
        { field: 'post_status', operator: 'equals', value: 'draft' },
        { field: 'post_author', operator: 'equals', value: '{{current_user_id}}' },
      ],
      groups: [],
    },
  ],
};

// ============================================================================
// Available Context Fixtures
// ============================================================================

export const mockAvailableContext = {
  Trigger: {
    user_id: { name: 'user_id', type: 'integer', description: 'User ID' },
    user_email: { name: 'user_email', type: 'string', description: 'User email' },
    user_login: { name: 'user_login', type: 'string', description: 'Username' },
  },
  send_email: {
    email_id: { name: 'email_id', type: 'string', description: 'Sent email ID' },
    sent_at: { name: 'sent_at', type: 'string', description: 'Timestamp when sent' },
  },
};

export const mockContextVariableGroups = [
  {
    namespace: 'Trigger',
    label: 'User Registration',
    variables: [
      { name: 'user_id', label: 'User ID', type: 'integer' },
      { name: 'user_email', label: 'User email', type: 'string' },
      { name: 'user_login', label: 'Username', type: 'string' },
    ],
  },
  {
    namespace: 'send_email',
    label: 'Send Email',
    variables: [
      { name: 'email_id', label: 'Sent email ID', type: 'string' },
      { name: 'sent_at', label: 'Timestamp when sent', type: 'string' },
    ],
  },
];

// ============================================================================
// Workflow Config Fixtures
// ============================================================================

export const mockWorkflowConfig = {
  trigger: {
    type: 'wordpress/user_registration',
    config: {},
    filters: null,
    integration: 'wordpress',
  },
  action: {
    id: ACTION_NODE_ID,
    label: 'send_email',
    type: 'wordpress/send_email',
    config: {
      to: '{{Trigger.user_email}}',
      subject: 'Welcome!',
      message: 'Thanks for registering!',
    },
    integration: 'wordpress',
  },
  layout: {
    nodes: [
      { id: TRIGGER_NODE_ID, position: { x: 250, y: 80 } },
      { id: ACTION_NODE_ID, position: { x: 250, y: 240 } },
    ],
    edges: [
      {
        id: `${TRIGGER_NODE_ID}-${ACTION_NODE_ID}`,
        source: TRIGGER_NODE_ID,
        target: ACTION_NODE_ID,
      },
    ],
  },
};

export const mockWorkflowConfigWithFilters = {
  ...mockWorkflowConfig,
  trigger: {
    ...mockWorkflowConfig.trigger,
    filters: mockFilterGroup,
  },
};

// ============================================================================
// API Response Fixtures
// ============================================================================

export const mockWorkflowResponse = {
  id: 1,
  name: 'Welcome Email Workflow',
  status: 'active',
  trigger_type: 'wordpress/user_registration',
  config: mockWorkflowConfig,
  created_at: '2024-01-15T10:30:00Z',
  updated_at: '2024-01-15T10:30:00Z',
};

export const mockCreateWorkflowResponse = {
  id: 999,
  name: 'New Workflow',
  status: 'inactive',
  trigger_type: null,
  config: null,
  created_at: '2024-01-16T12:00:00Z',
  updated_at: '2024-01-16T12:00:00Z',
};

export const mockActivityLogs = [
  {
    id: 1,
    workflow_id: 1,
    execution_id: 'exec-123',
    level: 'info',
    message: 'Workflow started',
    context: { trigger_type: 'wordpress/user_registration' },
    created_at: '2024-01-15T10:30:00Z',
  },
  {
    id: 2,
    workflow_id: 1,
    execution_id: 'exec-123',
    level: 'info',
    message: 'Action executed: send_email',
    context: { action_type: 'wordpress/send_email' },
    created_at: '2024-01-15T10:30:01Z',
  },
  {
    id: 3,
    workflow_id: 1,
    execution_id: 'exec-123',
    level: 'info',
    message: 'Workflow completed',
    context: {},
    created_at: '2024-01-15T10:30:02Z',
  },
];

// ============================================================================
// Dynamic Options Fixtures
// ============================================================================

export const mockMailchimpLists = [
  { id: 'list-1', name: 'Newsletter Subscribers' },
  { id: 'list-2', name: 'Premium Members' },
  { id: 'list-3', name: 'Beta Testers' },
];

export const mockMailchimpTags = [
  { id: 'tag-1', name: 'Active' },
  { id: 'tag-2', name: 'VIP' },
  { id: 'tag-3', name: 'New' },
];

export const mockAirtableFields = [
  { id: 'fld1', name: 'Name', type: 'singleLineText' },
  { id: 'fld2', name: 'Email', type: 'email' },
  { id: 'fld3', name: 'Status', type: 'singleSelect' },
];

// ============================================================================
// Error Fixtures
// ============================================================================

export const mockApiError = {
  code: 'rest_invalid_param',
  message: 'Invalid parameter(s): email',
  data: {
    status: 400,
    errors: [
      {
        code: 'invalid_email',
        message: 'The email address is not valid.',
        context: 'email',
      },
    ],
  },
};

export const mockValidationError = {
  code: 'rest_workflow_validation_failed',
  message: 'Workflow validation failed',
  data: {
    status: 400,
    errors: [
      {
        code: 'missing_required_field',
        message: 'The "to" field is required.',
        context: 'action.send_email.to',
      },
    ],
  },
};

// ============================================================================
// Type-Safe Factory Functions
// ============================================================================

import type { TriggerField } from '../../types/trigger';
import type { ActionConfig, WorkflowConfig, TriggerConfig } from '../../types/workflow';
import type { ActivityLog } from '../../types/activity';
import type { ContextVariable } from '../../types/workflow-context';
import type { ActionField, ActionSchema } from '../../types/action';

/**
 * Create a mock TriggerField with all required properties
 */
export function createMockTriggerField(overrides: Partial<TriggerField> = {}): TriggerField {
  return {
    name: 'user_email',
    type: 'string',
    description: 'User email address',
    example: 'user@example.com',
    ...overrides,
  };
}

/**
 * Create a mock ActionConfig with all required properties
 */
export function createMockActionConfig(overrides: Partial<ActionConfig> = {}): ActionConfig {
  return {
    id: 'action-1',
    type: 'wordpress/send_email',
    config: {},
    ...overrides,
  };
}

/**
 * Create a mock TriggerConfig with all required properties
 */
export function createMockTriggerConfig(overrides: Partial<TriggerConfig> = {}): TriggerConfig {
  return {
    type: 'wordpress/user_registration',
    config: {},
    ...overrides,
  };
}

/**
 * Create a mock WorkflowConfig with all required properties
 */
export function createMockWorkflowConfig(overrides: Partial<WorkflowConfig> = {}): WorkflowConfig {
  return {
    trigger: createMockTriggerConfig(),
    actions: { [createMockActionConfig().id]: createMockActionConfig() },
    ...overrides,
  };
}

/**
 * Create a mock ActivityLog with all required properties
 */
export function createMockActivityLog(overrides: Partial<ActivityLog> = {}): ActivityLog {
  return {
    id: 1,
    workflow_id: 1,
    level: 'info',
    message: 'Workflow executed',
    context: {},
    created_at: '2024-01-15T10:30:00Z',
    ...overrides,
  };
}

/**
 * Create a mock ContextVariable with all required properties
 */
export function createMockContextVariable(
  overrides: Partial<ContextVariable> = {},
): ContextVariable {
  return {
    path: 'Trigger.user_email',
    label: 'User Email',
    source: 'User Registration',
    namespace: 'Trigger',
    type: 'string',
    description: 'The email address of the registered user',
    example: 'user@example.com',
    ...overrides,
  };
}

/**
 * Create a mock ActionField with all required properties
 */
export function createMockActionField(overrides: Partial<ActionField> = {}): ActionField {
  return {
    type: 'string',
    label: 'Field',
    description: 'A test field',
    required: false,
    ...overrides,
  };
}

/**
 * Helper to create a minimal valid ActionSchema
 */
export function createMockActionSchema(fields: Record<string, Partial<ActionField>>): ActionSchema {
  const schema: ActionSchema = {};
  for (const [key, field] of Object.entries(fields)) {
    schema[key] = createMockActionField(field);
  }
  return schema;
}
