import { describe, it, expect } from 'vitest'
import { mapSimVsmLink } from '../link-mapper'
import type { SimVsmParsedLink } from '../types'

let counter = 0
const idFactory = () => `c${++counter}`

describe('mapSimVsmLink', () => {
  it('maps materialFlow with kind absent (default) and no label when there is no text', () => {
    const link: SimVsmParsedLink = { key: '-1', simvsmClass: 'materialFlow', fromKey: 'a', toKey: 'b' }
    const outcome = mapSimVsmLink(link, new Map([['a', 'na'], ['b', 'nb']]), idFactory)
    expect(outcome.supported).toBe(true)
    expect(outcome.connection).toMatchObject({ fromNodeId: 'na', toNodeId: 'nb' })
    expect(outcome.connection?.kind).toBeUndefined()
  })

  it('maps informationFlow with kind "information" and text as frequency (not label)', () => {
    const link: SimVsmParsedLink = { key: '-1', simvsmClass: 'informationFlow', fromKey: 'a', toKey: 'b', text: 'täglich' }
    const outcome = mapSimVsmLink(link, new Map([['a', 'na'], ['b', 'nb']]), idFactory)
    expect(outcome.connection).toMatchObject({ kind: 'information', frequency: 'täglich' })
    expect(outcome.connection?.label).toBeUndefined()
  })

  it('puts materialFlow text into label, not frequency', () => {
    const link: SimVsmParsedLink = { key: '-1', simvsmClass: 'materialFlow', fromKey: 'a', toKey: 'b', text: 'Behälter' }
    const outcome = mapSimVsmLink(link, new Map([['a', 'na'], ['b', 'nb']]), idFactory)
    expect(outcome.connection?.label).toBe('Behälter')
    expect(outcome.connection?.frequency).toBeUndefined()
  })

  it('reports a missing relationship (unsupported, no connection) when an endpoint was not mapped', () => {
    const link: SimVsmParsedLink = { key: '-1', simvsmClass: 'informationFlow', fromKey: 'a', toKey: 'unmapped-note' }
    const outcome = mapSimVsmLink(link, new Map([['a', 'na']]), idFactory)
    expect(outcome.supported).toBe(false)
    expect(outcome.connection).toBeNull()
    expect(outcome.reasonDe).toBeTruthy()
  })

  it('reports the image link class as unsupported', () => {
    const link: SimVsmParsedLink = { key: '-1', simvsmClass: 'image', fromKey: 'a', toKey: 'b' }
    const outcome = mapSimVsmLink(link, new Map([['a', 'na'], ['b', 'nb']]), idFactory)
    expect(outcome.supported).toBe(false)
  })

  it('reports a truly unknown link class as unsupported with its own reason', () => {
    const link: SimVsmParsedLink = { key: '-1', simvsmClass: 'brandNewLinkClass', fromKey: 'a', toKey: 'b' }
    const outcome = mapSimVsmLink(link, new Map([['a', 'na'], ['b', 'nb']]), idFactory)
    expect(outcome.supported).toBe(false)
    expect(outcome.reasonDe).toContain('Unbekannte Verbindungsart')
  })
})
