/**
 * Test: Registry Serialization - buildEdges
 * Tests for buildEdges function that creates Command View edges from resource relationships
 */

import { describe, it, expect } from 'vitest'
import { buildEdges } from '../serialization'
import type { DeploymentSpec } from '../resource-registry'
import type {
  TriggerDefinition,
  ExternalResourceDefinition,
  HumanCheckpointDefinition,
  ResourceRelationships
} from '../types'
import type { CommandViewEdge } from '../command-view'

describe('buildEdges', () => {
  describe('Trigger Edges', () => {
    it('creates "triggers" edge for trigger -> workflow', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-webhook',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Order Webhook',
        description: 'Webhook for new orders',
        version: '1.0.0',
        status: 'prod'
      }

      const relationships: ResourceRelationships = {
        'trigger-webhook': {
          triggers: { workflows: ['order-workflow'] }
        }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'trigger-webhook',
        target: 'order-workflow',
        relationship: 'triggers'
      })
    })

    it('creates "triggers" edge for trigger -> agent', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-schedule',
        type: 'trigger',
        triggerType: 'schedule',
        name: 'Daily Report',
        description: 'Daily report trigger',
        version: '1.0.0',
        status: 'prod',
        schedule: '0 6 * * *'
      }

      const relationships: ResourceRelationships = {
        'trigger-schedule': {
          triggers: { agents: ['report-agent'] }
        }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'trigger-schedule',
        target: 'report-agent',
        relationship: 'triggers'
      })
    })

    it('creates "triggers" edge for trigger -> externalResource (via relationships)', () => {
      // Note: trigger -> externalResource edges are created via ResourceRelationships
      // The triggers.externalResources field doesn't exist - use relationships instead
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-event',
        type: 'trigger',
        triggerType: 'event',
        name: 'Low Stock Event',
        description: 'Triggers on low stock',
        version: '1.0.0',
        status: 'prod',
        eventType: 'low-stock-alert'
      }

      // Note: ResourceRelationships.triggers only supports agents/workflows
      // For external resources, edges come from ExternalResourceDefinition.triggers (external -> internal)
      // There's no mechanism for trigger -> external edges in the current model
      const resources: DeploymentSpec = {
        triggers: [trigger]
      }

      const edges = buildEdges(resources)

      // No edges created - trigger -> external relationships are not supported
      // External resources declare what THEY trigger (external -> internal), not the reverse
      expect(edges).toHaveLength(0)
    })

    it('handles triggers with multiple targets', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-multi',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Multi Target Trigger',
        description: 'Triggers multiple resources',
        version: '1.0.0',
        status: 'prod'
      }

      const relationships: ResourceRelationships = {
        'trigger-multi': {
          triggers: {
            workflows: ['workflow-1', 'workflow-2'],
            agents: ['agent-1']
          }
        }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships
      }

      const edges = buildEdges(resources)

      // Note: ResourceRelationships only supports agents/workflows, not externalResources
      expect(edges).toHaveLength(3)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'trigger-multi',
          target: 'agent-1',
          relationship: 'triggers'
        },
        {
          id: 'edge-1',
          source: 'trigger-multi',
          target: 'workflow-1',
          relationship: 'triggers'
        },
        {
          id: 'edge-2',
          source: 'trigger-multi',
          target: 'workflow-2',
          relationship: 'triggers'
        }
      ])
    })

    it('handles triggers with no targets (empty relationships)', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-empty',
        type: 'trigger',
        triggerType: 'manual',
        name: 'Manual Trigger',
        description: 'Manual trigger with no targets',
        version: '1.0.0',
        status: 'dev'
      }

      const relationships: ResourceRelationships = {
        'trigger-empty': {
          triggers: {
            workflows: [],
            agents: []
          }
        }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
    })

    it('handles triggers with no relationships declared', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-no-targets',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'No Targets Trigger',
        description: 'Trigger without relationships',
        version: '1.0.0',
        status: 'dev'
      }

      const resources: DeploymentSpec = {
        triggers: [trigger]
        // No relationships declared for this trigger
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
    })
  })

  describe('Relationship Edges', () => {
    it('creates "triggers" edge for resource -> agent relationship', () => {
      const relationships: ResourceRelationships = {
        'order-processor': {
          triggers: {
            agents: ['fulfillment-agent']
          }
        }
      }

      const resources: DeploymentSpec = {
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'order-processor',
        target: 'fulfillment-agent',
        relationship: 'triggers'
      })
    })

    it('creates "triggers" edge for resource -> workflow relationship', () => {
      const relationships: ResourceRelationships = {
        'triage-agent': {
          triggers: {
            workflows: ['escalation-workflow']
          }
        }
      }

      const resources: DeploymentSpec = {
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'triage-agent',
        target: 'escalation-workflow',
        relationship: 'triggers'
      })
    })

    it('creates "uses" edge for resource -> integration relationship', () => {
      const relationships: ResourceRelationships = {
        'data-sync-workflow': {
          uses: {
            integrations: ['integration-postgres', 'integration-shopify']
          }
        }
      }

      const resources: DeploymentSpec = {
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(2)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'data-sync-workflow',
          target: 'integration-postgres',
          relationship: 'uses'
        },
        {
          id: 'edge-1',
          source: 'data-sync-workflow',
          target: 'integration-shopify',
          relationship: 'uses'
        }
      ])
    })

    it('handles relationships with all relationship types', () => {
      const relationships: ResourceRelationships = {
        'complex-agent': {
          triggers: {
            agents: ['agent-1', 'agent-2'],
            workflows: ['workflow-1']
          },
          uses: {
            integrations: ['integration-1', 'integration-2']
          }
        }
      }

      const resources: DeploymentSpec = {
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(5)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'complex-agent',
          target: 'agent-1',
          relationship: 'triggers'
        },
        {
          id: 'edge-1',
          source: 'complex-agent',
          target: 'agent-2',
          relationship: 'triggers'
        },
        {
          id: 'edge-2',
          source: 'complex-agent',
          target: 'workflow-1',
          relationship: 'triggers'
        },
        {
          id: 'edge-3',
          source: 'complex-agent',
          target: 'integration-1',
          relationship: 'uses'
        },
        {
          id: 'edge-4',
          source: 'complex-agent',
          target: 'integration-2',
          relationship: 'uses'
        }
      ])
    })

    it('handles empty relationships map', () => {
      const relationships: ResourceRelationships = {}

      const resources: DeploymentSpec = {
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
    })

    it('handles undefined relationships', () => {
      const resources: DeploymentSpec = {
        // No relationships field
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
    })
  })

  describe('External Resource Edges', () => {
    it('creates "triggers" edge for external -> workflow', () => {
      const external: ExternalResourceDefinition = {
        resourceId: 'external-n8n-sync',
        type: 'external',
        platform: 'n8n',
        name: 'Order Sync',
        description: 'Legacy n8n order sync',
        version: '1.0.0',
        status: 'prod',
        triggers: {
          workflows: ['order-fulfillment']
        }
      }

      const resources: DeploymentSpec = {
        externalResources: [external]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'external-n8n-sync',
        target: 'order-fulfillment',
        relationship: 'triggers'
      })
    })

    it('creates "triggers" edge for external -> agent', () => {
      const external: ExternalResourceDefinition = {
        resourceId: 'external-zapier-lead',
        type: 'external',
        platform: 'zapier',
        name: 'Lead Capture',
        description: 'Zapier lead capture',
        version: '1.0.0',
        status: 'prod',
        triggers: {
          agents: ['lead-router-agent']
        }
      }

      const resources: DeploymentSpec = {
        externalResources: [external]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'external-zapier-lead',
        target: 'lead-router-agent',
        relationship: 'triggers'
      })
    })

    it('creates "uses" edge for external -> integration', () => {
      const external: ExternalResourceDefinition = {
        resourceId: 'external-make-crm',
        type: 'external',
        platform: 'make',
        name: 'CRM Sync',
        description: 'Make CRM sync',
        version: '1.0.0',
        status: 'prod',
        uses: {
          integrations: ['integration-salesforce']
        }
      }

      const resources: DeploymentSpec = {
        externalResources: [external]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'external-make-crm',
        target: 'integration-salesforce',
        relationship: 'uses'
      })
    })

    it('does NOT create edges for triggeredBy (removed field)', () => {
      // This test verifies the field was removed and edges are forward-only
      const external: ExternalResourceDefinition = {
        resourceId: 'external-legacy',
        type: 'external',
        platform: 'n8n',
        name: 'Legacy Automation',
        description: 'Legacy automation',
        version: '1.0.0',
        status: 'dev'
        // No triggeredBy field - it was removed per relationship-consolidation
      }

      const resources: DeploymentSpec = {
        externalResources: [external]
      }

      const edges = buildEdges(resources)

      // Should produce no edges since external has no forward relationships
      expect(edges).toHaveLength(0)
    })

    it('handles external resources with no relationships', () => {
      const external: ExternalResourceDefinition = {
        resourceId: 'external-isolated',
        type: 'external',
        platform: 'other',
        name: 'Isolated Automation',
        description: 'No relationships',
        version: '1.0.0',
        status: 'dev'
        // No triggers or uses
      }

      const resources: DeploymentSpec = {
        externalResources: [external]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
    })

    it('handles external resources with all relationship types', () => {
      const external: ExternalResourceDefinition = {
        resourceId: 'external-complex',
        type: 'external',
        platform: 'n8n',
        name: 'Complex Automation',
        description: 'Complex external automation',
        version: '1.0.0',
        status: 'prod',
        triggers: {
          workflows: ['workflow-1'],
          agents: ['agent-1', 'agent-2']
        },
        uses: {
          integrations: ['integration-1']
        }
      }

      const resources: DeploymentSpec = {
        externalResources: [external]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(4)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'external-complex',
          target: 'workflow-1',
          relationship: 'triggers'
        },
        {
          id: 'edge-1',
          source: 'external-complex',
          target: 'agent-1',
          relationship: 'triggers'
        },
        {
          id: 'edge-2',
          source: 'external-complex',
          target: 'agent-2',
          relationship: 'triggers'
        },
        {
          id: 'edge-3',
          source: 'external-complex',
          target: 'integration-1',
          relationship: 'uses'
        }
      ])
    })
  })

  describe('Human Checkpoint Edges', () => {
    it('creates "approval" edge for agent -> humanCheckpoint (requestedBy)', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-sales',
        type: 'human',
        name: 'Sales Approval',
        description: 'Sales team approval queue',
        version: '1.0.0',
        status: 'prod',
        requestedBy: {
          agents: ['order-processor-agent']
        }
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'order-processor-agent',
        target: 'approval-sales',
        relationship: 'approval'
      })
    })

    it('creates "approval" edge for workflow -> humanCheckpoint (requestedBy)', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-refund',
        type: 'human',
        name: 'Refund Approval',
        description: 'Refund approval queue',
        version: '1.0.0',
        status: 'prod',
        requestedBy: {
          workflows: ['refund-workflow']
        }
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'refund-workflow',
        target: 'approval-refund',
        relationship: 'approval'
      })
    })

    it('creates "triggers" edge for humanCheckpoint -> agent (routesTo)', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-content',
        type: 'human',
        name: 'Content Approval',
        description: 'Content approval queue',
        version: '1.0.0',
        status: 'prod',
        routesTo: {
          agents: ['publisher-agent']
        }
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'approval-content',
        target: 'publisher-agent',
        relationship: 'triggers'
      })
    })

    it('creates "triggers" edge for humanCheckpoint -> workflow (routesTo)', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-budget',
        type: 'human',
        name: 'Budget Approval',
        description: 'Budget approval queue',
        version: '1.0.0',
        status: 'prod',
        routesTo: {
          workflows: ['procurement-workflow']
        }
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(1)
      expect(edges[0]).toEqual({
        id: 'edge-0',
        source: 'approval-budget',
        target: 'procurement-workflow',
        relationship: 'triggers'
      })
    })

    it('handles human checkpoints with only requestedBy', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-review-only',
        type: 'human',
        name: 'Review Only',
        description: 'Review only checkpoint',
        version: '1.0.0',
        status: 'dev',
        requestedBy: {
          agents: ['agent-1', 'agent-2'],
          workflows: ['workflow-1']
        }
        // No routesTo
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(3)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'agent-1',
          target: 'approval-review-only',
          relationship: 'approval'
        },
        {
          id: 'edge-1',
          source: 'agent-2',
          target: 'approval-review-only',
          relationship: 'approval'
        },
        {
          id: 'edge-2',
          source: 'workflow-1',
          target: 'approval-review-only',
          relationship: 'approval'
        }
      ])
    })

    it('handles human checkpoints with only routesTo', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-dispatch-only',
        type: 'human',
        name: 'Dispatch Only',
        description: 'Dispatch only checkpoint',
        version: '1.0.0',
        status: 'dev',
        // No requestedBy
        routesTo: {
          agents: ['agent-3'],
          workflows: ['workflow-2', 'workflow-3']
        }
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(3)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'approval-dispatch-only',
          target: 'agent-3',
          relationship: 'triggers'
        },
        {
          id: 'edge-1',
          source: 'approval-dispatch-only',
          target: 'workflow-2',
          relationship: 'triggers'
        },
        {
          id: 'edge-2',
          source: 'approval-dispatch-only',
          target: 'workflow-3',
          relationship: 'triggers'
        }
      ])
    })

    it('handles human checkpoints with both requestedBy and routesTo', () => {
      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-full',
        type: 'human',
        name: 'Full Approval',
        description: 'Full approval with both directions',
        version: '1.0.0',
        status: 'prod',
        requestedBy: {
          agents: ['triage-agent'],
          workflows: ['intake-workflow']
        },
        routesTo: {
          agents: ['fulfillment-agent'],
          workflows: ['processing-workflow']
        }
      }

      const resources: DeploymentSpec = {
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(4)
      expect(edges).toEqual([
        {
          id: 'edge-0',
          source: 'triage-agent',
          target: 'approval-full',
          relationship: 'approval'
        },
        {
          id: 'edge-1',
          source: 'intake-workflow',
          target: 'approval-full',
          relationship: 'approval'
        },
        {
          id: 'edge-2',
          source: 'approval-full',
          target: 'fulfillment-agent',
          relationship: 'triggers'
        },
        {
          id: 'edge-3',
          source: 'approval-full',
          target: 'processing-workflow',
          relationship: 'triggers'
        }
      ])
    })
  })

  describe('Edge ID Generation', () => {
    it('generates unique edge IDs across all edge types', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-1',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Trigger',
        description: 'Test trigger',
        version: '1.0.0',
        status: 'dev'
      }

      const relationships: ResourceRelationships = {
        'trigger-1': {
          triggers: { workflows: ['workflow-1'] }
        },
        'agent-1': {
          uses: { integrations: ['integration-1'] }
        }
      }

      const external: ExternalResourceDefinition = {
        resourceId: 'external-1',
        type: 'external',
        platform: 'n8n',
        name: 'External',
        description: 'Test external',
        version: '1.0.0',
        status: 'dev',
        triggers: { agents: ['agent-2'] }
      }

      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-1',
        type: 'human',
        name: 'Approval',
        description: 'Test approval',
        version: '1.0.0',
        status: 'dev',
        requestedBy: { agents: ['agent-3'] }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships,
        externalResources: [external],
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      // Verify all edge IDs are unique and sequential
      const edgeIds = edges.map((e) => e.id)
      expect(edgeIds).toEqual(['edge-0', 'edge-1', 'edge-2', 'edge-3'])

      // Verify no duplicates
      const uniqueIds = new Set(edgeIds)
      expect(uniqueIds.size).toBe(edgeIds.length)
    })

    it('maintains sequential edge numbering starting from 0', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-multi',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Multi',
        description: 'Multi-target trigger',
        version: '1.0.0',
        status: 'dev'
      }

      const relationships: ResourceRelationships = {
        'trigger-multi': {
          triggers: {
            workflows: ['w1', 'w2'],
            agents: ['a1', 'a2', 'a3']
          }
        }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(5)
      expect(edges[0].id).toBe('edge-0')
      expect(edges[1].id).toBe('edge-1')
      expect(edges[2].id).toBe('edge-2')
      expect(edges[3].id).toBe('edge-3')
      expect(edges[4].id).toBe('edge-4')
    })
  })

  describe('Edge Type Consolidation', () => {
    it('only produces edges with types: triggers, uses, approval', () => {
      // Create a comprehensive set of resources to test all edge types
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-1',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Trigger',
        description: 'Test',
        version: '1.0.0',
        status: 'dev'
      }

      const relationships: ResourceRelationships = {
        'trigger-1': {
          triggers: { workflows: ['workflow-1'] }
        },
        'agent-1': {
          triggers: { agents: ['agent-2'] },
          uses: { integrations: ['integration-1'] }
        }
      }

      const external: ExternalResourceDefinition = {
        resourceId: 'external-1',
        type: 'external',
        platform: 'n8n',
        name: 'External',
        description: 'Test',
        version: '1.0.0',
        status: 'dev',
        triggers: { workflows: ['workflow-2'] },
        uses: { integrations: ['integration-2'] }
      }

      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-1',
        type: 'human',
        name: 'Approval',
        description: 'Test',
        version: '1.0.0',
        status: 'dev',
        requestedBy: { agents: ['agent-3'] },
        routesTo: { workflows: ['workflow-3'] }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships,
        externalResources: [external],
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      // Verify ALL edges have one of the three allowed relationship types
      const relationshipTypes = edges.map((e) => e.relationship)
      const allowedTypes: CommandViewEdge['relationship'][] = ['triggers', 'uses', 'approval']

      for (const relType of relationshipTypes) {
        expect(allowedTypes).toContain(relType)
      }

      // Count each type
      const typeCount = {
        triggers: relationshipTypes.filter((t) => t === 'triggers').length,
        uses: relationshipTypes.filter((t) => t === 'uses').length,
        approval: relationshipTypes.filter((t) => t === 'approval').length
      }

      // Verify we have edges of each type (comprehensive test)
      expect(typeCount.triggers).toBeGreaterThan(0)
      expect(typeCount.uses).toBeGreaterThan(0)
      expect(typeCount.approval).toBeGreaterThan(0)

      // Verify total matches sum (no other edge types)
      expect(edges.length).toBe(typeCount.triggers + typeCount.uses + typeCount.approval)
    })

    it('does NOT produce edges with type: invokes', () => {
      // This test verifies the old 'invokes' edge type is gone
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-test',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Test',
        description: 'Test trigger',
        version: '1.0.0',
        status: 'dev'
      }

      const relationships: ResourceRelationships = {
        'trigger-test': {
          triggers: {
            workflows: ['workflow-1'],
            agents: ['agent-1']
          }
        }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships
      }

      const edges = buildEdges(resources)

      // Verify no edge has relationship 'invokes'
      const hasInvokesEdge = edges.some((e: CommandViewEdge) => {
        // Use type assertion to check for the old type
        return (e.relationship as string) === 'invokes'
      })

      expect(hasInvokesEdge).toBe(false)

      // All edges should be 'triggers' in this case
      edges.forEach((edge) => {
        expect(edge.relationship).toBe('triggers')
      })
    })
  })

  describe('Complex Multi-Resource Scenarios', () => {
    it('handles organization with all resource types', () => {
      const trigger: TriggerDefinition = {
        resourceId: 'trigger-order',
        type: 'trigger',
        triggerType: 'webhook',
        name: 'Order Webhook',
        description: 'New orders',
        version: '1.0.0',
        status: 'prod'
      }

      const relationships: ResourceRelationships = {
        'trigger-order': {
          triggers: { workflows: ['order-workflow'] }
        },
        'order-workflow': {
          triggers: { agents: ['fulfillment-agent'] },
          uses: { integrations: ['integration-shopify'] }
        },
        'fulfillment-agent': {
          uses: { integrations: ['integration-shipstation'] }
        }
      }

      const external: ExternalResourceDefinition = {
        resourceId: 'external-inventory',
        type: 'external',
        platform: 'n8n',
        name: 'Inventory Sync',
        description: 'Legacy inventory sync',
        version: '1.0.0',
        status: 'prod',
        uses: { integrations: ['integration-postgres'] }
      }

      const humanCheckpoint: HumanCheckpointDefinition = {
        resourceId: 'approval-high-value',
        type: 'human',
        name: 'High Value Orders',
        description: 'Manual approval for high value',
        version: '1.0.0',
        status: 'prod',
        requestedBy: { agents: ['fulfillment-agent'] },
        routesTo: { workflows: ['special-handling-workflow'] }
      }

      const resources: DeploymentSpec = {
        triggers: [trigger],
        relationships,
        externalResources: [external],
        humanCheckpoints: [humanCheckpoint]
      }

      const edges = buildEdges(resources)

      // Verify we got edges from all sources
      const sourceIds = new Set(edges.map((e) => e.source))
      expect(sourceIds).toContain('trigger-order')
      expect(sourceIds).toContain('order-workflow')
      expect(sourceIds).toContain('fulfillment-agent')
      expect(sourceIds).toContain('external-inventory')
      expect(sourceIds).toContain('approval-high-value')

      // Verify relationship type distribution
      const relationshipTypes = edges.map((e) => e.relationship)
      expect(relationshipTypes).toContain('triggers')
      expect(relationshipTypes).toContain('uses')
      expect(relationshipTypes).toContain('approval')
    })

    it('handles empty organization resources', () => {
      const resources: DeploymentSpec = {}

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
      expect(edges).toEqual([])
    })

    it('handles organization with only empty arrays', () => {
      const resources: DeploymentSpec = {
        triggers: [],
        externalResources: [],
        humanCheckpoints: [],
        relationships: {}
      }

      const edges = buildEdges(resources)

      expect(edges).toHaveLength(0)
    })
  })
})
