import { Prisma, PrismaClient } from '@prisma/client';

/**
 * Mock workflow data with DSL, versions, instances, and node executions.
 */
const WORKFLOWS = [
  {
    code: 'daily_data_sync',
    name: '每日数据同步',
    description: '每天凌晨2点从外部API同步用户数据到本地数据库',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'admin',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'cron_trigger',
          label: 'Cron 触发',
          position: { x: 100, y: 200 },
        },
        {
          id: 'action_1',
          type: 'http_request',
          label: '拉取外部数据',
          position: { x: 350, y: 200 },
        },
        {
          id: 'action_2',
          type: 'code',
          label: '数据转换',
          position: { x: 600, y: 200 },
        },
        {
          id: 'action_3',
          type: 'db_execute',
          label: '写入数据库',
          position: { x: 850, y: 200 },
        },
        {
          id: 'action_4',
          type: 'send_notification',
          label: '发送通知',
          position: { x: 1100, y: 200 },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        { id: 'e-action_1-action_2', source: 'action_1', target: 'action_2' },
        { id: 'e-action_2-action_3', source: 'action_2', target: 'action_3' },
        { id: 'e-action_3-action_4', source: 'action_3', target: 'action_4' },
      ],
    },
  },
  {
    code: 'user_reg_approval',
    name: '新用户注册审批',
    description: '新用户注册后触发审批流程，管理员审批通过后发送欢迎邮件',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'admin',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'webhook_trigger',
          label: 'Webhook 接收注册',
          position: { x: 100, y: 200 },
        },
        {
          id: 'action_1',
          type: 'set_variable',
          label: '提取用户信息',
          position: { x: 350, y: 200 },
        },
        {
          id: 'approval_1',
          type: 'approval',
          label: '管理员审批',
          position: { x: 600, y: 200 },
        },
        {
          id: 'condition_1',
          type: 'if_else',
          label: '审批结果判断',
          position: { x: 850, y: 200 },
        },
        {
          id: 'action_2',
          type: 'db_execute',
          label: '激活用户',
          position: { x: 1100, y: 100 },
        },
        {
          id: 'action_3',
          type: 'send_notification',
          label: '发送欢迎邮件',
          position: { x: 1350, y: 100 },
        },
        {
          id: 'action_4',
          type: 'send_notification',
          label: '发送拒绝通知',
          position: { x: 1100, y: 300 },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        {
          id: 'e-action_1-approval_1',
          source: 'action_1',
          target: 'approval_1',
        },
        {
          id: 'e-approval_1-condition_1',
          source: 'approval_1',
          target: 'condition_1',
        },
        {
          id: 'e-condition_1-action_2',
          source: 'condition_1',
          target: 'action_2',
          label: 'true',
        },
        {
          id: 'e-condition_1-action_4',
          source: 'condition_1',
          target: 'action_4',
          label: 'false',
        },
        { id: 'e-action_2-action_3', source: 'action_2', target: 'action_3' },
      ],
    },
  },
  {
    code: 'error_monitor_alert',
    name: '异常监控告警',
    description: '监听系统事件，当错误率超过阈值时触发告警通知',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'system',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'event_trigger',
          label: '监听错误事件',
          position: { x: 100, y: 200 },
        },
        {
          id: 'action_1',
          type: 'db_query',
          label: '查询近5分钟错误数',
          position: { x: 350, y: 200 },
        },
        {
          id: 'condition_1',
          type: 'if_else',
          label: '错误率 > 5%?',
          position: { x: 600, y: 200 },
        },
        {
          id: 'action_2',
          type: 'send_notification',
          label: '发送告警',
          position: { x: 850, y: 100 },
        },
        {
          id: 'action_3',
          type: 'code',
          label: '记录日志',
          position: { x: 850, y: 300 },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        {
          id: 'e-action_1-condition_1',
          source: 'action_1',
          target: 'condition_1',
        },
        {
          id: 'e-condition_1-action_2',
          source: 'condition_1',
          target: 'action_2',
          label: 'true',
        },
        {
          id: 'e-condition_1-action_3',
          source: 'condition_1',
          target: 'action_3',
          label: 'false',
        },
      ],
    },
  },
  {
    code: 'batch_data_export',
    name: '批量数据导出',
    description: '手动触发导出指定表的数据为CSV文件并发送邮件',
    status: 'DRAFT' as const,
    isEnabled: false,
    creator: 'admin',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'manual_trigger',
          label: '手动触发',
          position: { x: 100, y: 200 },
        },
        {
          id: 'action_1',
          type: 'db_query',
          label: '查询数据',
          position: { x: 350, y: 200 },
        },
        {
          id: 'loop_1',
          type: 'for_each',
          label: '遍历分页',
          position: { x: 600, y: 200 },
        },
        {
          id: 'action_2',
          type: 'code',
          label: '转换为CSV',
          position: { x: 850, y: 200 },
        },
        {
          id: 'action_3',
          type: 'send_notification',
          label: '发送邮件',
          position: { x: 1100, y: 200 },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        { id: 'e-action_1-loop_1', source: 'action_1', target: 'loop_1' },
        { id: 'e-loop_1-action_2', source: 'loop_1', target: 'action_2' },
        { id: 'e-action_2-action_3', source: 'action_2', target: 'action_3' },
      ],
    },
  },
  {
    code: 'multi_env_deploy',
    name: '多环境部署流水线',
    description: '并行部署到staging和production环境，需人工审批production',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'devops',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'webhook_trigger',
          label: 'CI 回调',
          position: { x: 100, y: 200 },
        },
        {
          id: 'parallel_1',
          type: 'parallel',
          label: '并行部署',
          position: { x: 350, y: 200 },
        },
        {
          id: 'action_1',
          type: 'http_request',
          label: '部署 Staging',
          position: { x: 600, y: 100 },
        },
        {
          id: 'approval_1',
          type: 'approval',
          label: 'Production 审批',
          position: { x: 600, y: 300 },
        },
        {
          id: 'action_2',
          type: 'http_request',
          label: '部署 Production',
          position: { x: 850, y: 300 },
        },
        {
          id: 'action_3',
          type: 'send_notification',
          label: '部署完成通知',
          position: { x: 1100, y: 200 },
        },
      ],
      edges: [
        {
          id: 'e-trigger_1-parallel_1',
          source: 'trigger_1',
          target: 'parallel_1',
        },
        {
          id: 'e-parallel_1-action_1',
          source: 'parallel_1',
          target: 'action_1',
        },
        {
          id: 'e-parallel_1-approval_1',
          source: 'parallel_1',
          target: 'approval_1',
        },
        {
          id: 'e-approval_1-action_2',
          source: 'approval_1',
          target: 'action_2',
        },
        { id: 'e-action_1-action_3', source: 'action_1', target: 'action_3' },
        { id: 'e-action_2-action_3', source: 'action_2', target: 'action_3' },
      ],
    },
  },
  {
    code: 'user_role_change',
    name: '用户角色变更通知',
    description:
      '当 t_admin_user_role 表中用户角色发生变更时，记录审计日志并通知相关人员',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'admin',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'event_trigger',
          label: '监听角色变更事件',
          position: { x: 100, y: 200 },
          config: { eventName: 'user_role.updated' },
        },
        {
          id: 'action_1',
          type: 'db_query',
          label: '查询用户详情',
          position: { x: 350, y: 200 },
          config: {
            query:
              'SELECT userid, username, roles FROM t_admin_user_role WHERE userid = $1',
          },
        },
        {
          id: 'action_2',
          type: 'code',
          label: '对比角色差异',
          position: { x: 600, y: 200 },
          config: {
            script:
              'const prev = JSON.parse(input.previousRoles); const curr = JSON.parse(input.currentRoles); return { added: curr.filter(r => !prev.includes(r)), removed: prev.filter(r => !curr.includes(r)) };',
          },
        },
        {
          id: 'condition_1',
          type: 'if_else',
          label: '是否涉及ADMIN角色',
          position: { x: 850, y: 200 },
          config: {
            conditions: [
              { field: 'added', operator: 'contains', value: 'SYSTEM_ADMIN' },
            ],
          },
        },
        {
          id: 'action_3',
          type: 'send_notification',
          label: '发送安全告警',
          position: { x: 1100, y: 100 },
          config: {
            channel: 'wecom',
            recipients: ['security-team'],
            message: '用户 {{username}} 被授予 SYSTEM_ADMIN 角色',
          },
        },
        {
          id: 'action_4',
          type: 'db_execute',
          label: '写入审计日志',
          position: { x: 1100, y: 300 },
          config: { operation: 'insert', table: 't_admin_audit_log' },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        { id: 'e-action_1-action_2', source: 'action_1', target: 'action_2' },
        {
          id: 'e-action_2-condition_1',
          source: 'action_2',
          target: 'condition_1',
        },
        {
          id: 'e-condition_1-action_3',
          source: 'condition_1',
          target: 'action_3',
          label: 'true',
        },
        {
          id: 'e-condition_1-action_4',
          source: 'condition_1',
          target: 'action_4',
          label: 'false',
        },
        { id: 'e-action_3-action_4', source: 'action_3', target: 'action_4' },
      ],
    },
  },
  {
    code: 'event_remind_sync',
    name: 'Event活动提醒与同步',
    description:
      '当 t_event 表新增活动或活动即将开始时，自动同步到 ServiceNow 并通知参与人员',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'admin',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'cron_trigger',
          label: '每日9点检查',
          position: { x: 100, y: 200 },
          config: { cron: '0 9 * * *', timezone: 'Asia/Shanghai' },
        },
        {
          id: 'action_1',
          type: 'db_query',
          label: '查询3天内活动',
          position: { x: 350, y: 200 },
          config: {
            query:
              "SELECT * FROM t_event WHERE start_date BETWEEN NOW() AND NOW() + INTERVAL '3 days'",
          },
        },
        {
          id: 'condition_1',
          type: 'if_else',
          label: '有即将开始的活动?',
          position: { x: 600, y: 200 },
          config: {
            conditions: [{ field: 'rowCount', operator: 'gt', value: '0' }],
          },
        },
        {
          id: 'loop_1',
          type: 'for_each',
          label: '遍历活动列表',
          position: { x: 850, y: 150 },
          config: { iteratorField: 'rows', concurrency: 3 },
        },
        {
          id: 'condition_2',
          type: 'if_else',
          label: '已同步ServiceNow?',
          position: { x: 1100, y: 150 },
          config: {
            conditions: [
              {
                field: 'currentItem.sn_sys_id',
                operator: 'isNotEmpty',
                value: '',
              },
            ],
          },
        },
        {
          id: 'action_2',
          type: 'http_request',
          label: '同步到ServiceNow',
          position: { x: 1350, y: 80 },
          config: {
            url: 'https://servicenow.example.com/api/events',
            method: 'POST',
          },
        },
        {
          id: 'action_3',
          type: 'db_execute',
          label: '更新sn_sys_id',
          position: { x: 1600, y: 80 },
          config: { operation: 'update', table: 't_event', where: 'id = $1' },
        },
        {
          id: 'action_4',
          type: 'send_notification',
          label: '通知OIT负责人',
          position: { x: 1350, y: 250 },
          config: {
            channel: 'email',
            message:
              '活动 {{currentItem.city}} - {{currentItem.eventType}} 将于 {{currentItem.start_date}} 开始',
          },
        },
        {
          id: 'action_5',
          type: 'code',
          label: '记录检查完成',
          position: { x: 600, y: 350 },
          config: {
            script: 'return { checked: true, noUpcomingEvents: true };',
          },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        {
          id: 'e-action_1-condition_1',
          source: 'action_1',
          target: 'condition_1',
        },
        {
          id: 'e-condition_1-loop_1',
          source: 'condition_1',
          target: 'loop_1',
          label: 'true',
        },
        {
          id: 'e-condition_1-action_5',
          source: 'condition_1',
          target: 'action_5',
          label: 'false',
        },
        { id: 'e-loop_1-condition_2', source: 'loop_1', target: 'condition_2' },
        {
          id: 'e-condition_2-action_2',
          source: 'condition_2',
          target: 'action_2',
          label: 'false',
        },
        {
          id: 'e-condition_2-action_4',
          source: 'condition_2',
          target: 'action_4',
          label: 'true',
        },
        { id: 'e-action_2-action_3', source: 'action_2', target: 'action_3' },
        { id: 'e-action_3-action_4', source: 'action_3', target: 'action_4' },
      ],
    },
  },
  {
    code: 'new_user_onboard',
    name: '新增用户自动化流程',
    description:
      '当 t_admin_user_role 新增用户时，自动分配默认角色、同步到外部系统并发送欢迎通知',
    status: 'PUBLISHED' as const,
    isEnabled: true,
    creator: 'admin',
    dsl: {
      nodes: [
        {
          id: 'trigger_1',
          type: 'event_trigger',
          label: '监听用户创建事件',
          position: { x: 100, y: 200 },
          config: { eventName: 'user.created' },
        },
        {
          id: 'action_1',
          type: 'db_query',
          label: '查询新用户信息',
          position: { x: 350, y: 200 },
          config: {
            query:
              'SELECT userid, username, roles, is_active FROM t_admin_user_role WHERE userid = $1',
          },
        },
        {
          id: 'action_2',
          type: 'code',
          label: '初始化默认角色',
          position: { x: 600, y: 200 },
          config: {
            script:
              'const user = input.rows[0]; if (!user.roles || user.roles === "[]") { return { ...user, roles: JSON.stringify(["GUEST"]), needsUpdate: true }; } return { ...user, needsUpdate: false };',
          },
        },
        {
          id: 'condition_1',
          type: 'if_else',
          label: '需要分配默认角色?',
          position: { x: 850, y: 200 },
          config: {
            conditions: [
              { field: 'needsUpdate', operator: 'eq', value: 'true' },
            ],
          },
        },
        {
          id: 'action_3',
          type: 'db_execute',
          label: '写入默认角色',
          position: { x: 1100, y: 100 },
          config: {
            operation: 'update',
            table: 't_admin_user_role',
            data: { roles: '["GUEST"]' },
            where: 'userid = $1',
          },
        },
        {
          id: 'action_4',
          type: 'http_request',
          label: '同步到企业通讯录',
          position: { x: 1100, y: 300 },
          config: {
            url: 'https://api.wecom.example.com/user/sync',
            method: 'POST',
          },
        },
        {
          id: 'action_5',
          type: 'send_notification',
          label: '发送欢迎通知',
          position: { x: 1350, y: 200 },
          config: {
            channel: 'wecom',
            recipients: ['{{userid}}'],
            message:
              '欢迎加入系统！您的初始角色为 GUEST，如需更多权限请联系管理员。',
          },
        },
        {
          id: 'action_6',
          type: 'db_execute',
          label: '记录审计日志',
          position: { x: 1600, y: 200 },
          config: {
            operation: 'insert',
            table: 't_admin_audit_log',
            data: { action: 'user.onboarded', resource: 'user' },
          },
        },
      ],
      edges: [
        { id: 'e-trigger_1-action_1', source: 'trigger_1', target: 'action_1' },
        { id: 'e-action_1-action_2', source: 'action_1', target: 'action_2' },
        {
          id: 'e-action_2-condition_1',
          source: 'action_2',
          target: 'condition_1',
        },
        {
          id: 'e-condition_1-action_3',
          source: 'condition_1',
          target: 'action_3',
          label: 'true',
        },
        {
          id: 'e-condition_1-action_4',
          source: 'condition_1',
          target: 'action_4',
          label: 'false',
        },
        { id: 'e-action_3-action_4', source: 'action_3', target: 'action_4' },
        { id: 'e-action_4-action_5', source: 'action_4', target: 'action_5' },
        { id: 'e-action_5-action_6', source: 'action_5', target: 'action_6' },
      ],
    },
  },
];

export async function seedWorkflows(prisma: PrismaClient) {
  console.log('Seeding workflows...');

  for (const wf of WORKFLOWS) {
    // Upsert workflow by code
    const workflow = await prisma.workflow.upsert({
      where: { code: wf.code },
      update: {
        name: wf.name,
        description: wf.description,
        status: wf.status,
        isEnabled: wf.isEnabled,
        dsl: wf.dsl,
      },
      create: {
        code: wf.code,
        name: wf.name,
        description: wf.description,
        status: wf.status,
        isEnabled: wf.isEnabled,
        dsl: wf.dsl,
        creator: wf.creator,
      },
    });

    // Create version 1
    await prisma.workflowVersion.upsert({
      where: { workflowId_version: { workflowId: workflow.id, version: 1 } },
      update: {},
      create: {
        workflowId: workflow.id,
        version: 1,
        dsl: wf.dsl,
        prompt: `创建工作流: ${wf.name}`,
        changeSummary: '初始版本',
        creator: wf.creator,
      },
    });

    // For published workflows, create some mock instances
    if (wf.status === 'PUBLISHED') {
      const version = await prisma.workflowVersion.findFirst({
        where: { workflowId: workflow.id, version: 1 },
      });

      if (!version) continue;

      // Create 3 instances per published workflow with different statuses
      const instanceConfigs = [
        { status: 'COMPLETED' as const, daysAgo: 3 },
        { status: 'COMPLETED' as const, daysAgo: 1 },
        { status: 'RUNNING' as const, daysAgo: 0 },
      ];

      for (const cfg of instanceConfigs) {
        const startedAt = new Date(
          Date.now() - cfg.daysAgo * 24 * 60 * 60 * 1000,
        );
        const finishedAt =
          cfg.status === 'COMPLETED'
            ? new Date(startedAt.getTime() + 30000) // 30s later
            : null;

        const instance = await prisma.workflowInstance.create({
          data: {
            workflowId: workflow.id,
            versionId: version.id,
            status: cfg.status,
            context: { trigger: 'auto', env: 'production' },
            result:
              cfg.status === 'COMPLETED'
                ? { success: true, processedCount: 128 }
                : Prisma.JsonNull,
            startedAt,
            finishedAt,
            creator: wf.creator,
          },
        });

        // Create node executions for each instance
        const nodes = (wf.dsl as any).nodes || [];
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i];
          const nodeStarted = new Date(startedAt.getTime() + i * 5000);
          const isLastNode = i === nodes.length - 1;

          let nodeStatus: 'COMPLETED' | 'RUNNING' | 'PENDING' = 'COMPLETED';
          if (cfg.status === 'RUNNING') {
            if (i === nodes.length - 1) nodeStatus = 'RUNNING';
            if (i > nodes.length - 1) nodeStatus = 'PENDING';
          }

          await prisma.workflowNodeExecution.upsert({
            where: {
              instanceId_nodeId: { instanceId: instance.id, nodeId: node.id },
            },
            update: {},
            create: {
              instanceId: instance.id,
              nodeId: node.id,
              nodeType: node.type,
              nodeLabel: node.label,
              status: nodeStatus,
              input: { data: `mock_input_${i}` },
              output:
                nodeStatus === 'COMPLETED'
                  ? { data: `mock_output_${i}` }
                  : Prisma.JsonNull,
              startedAt: nodeStarted,
              finishedAt:
                nodeStatus === 'COMPLETED'
                  ? new Date(nodeStarted.getTime() + 3000)
                  : null,
            },
          });
        }
      }
    }
  }

  console.log(
    `Seeded ${WORKFLOWS.length} workflows with versions, instances, and node executions.`,
  );
}
