import test from 'node:test'
import assert from 'node:assert/strict'
import { buildErGraph } from './erGraph.js'

test('buildErGraph creates table nodes with primary and required fields', () => {
  const graph = buildErGraph([
    {
      tableName: 'department',
      tableComment: '院系表',
      columns: [
        { columnName: 'id', columnComment: '主键ID', isPk: '1', isRequired: '1' },
        { columnName: 'dept_name', columnComment: '院系名称', isRequired: '1' }
      ]
    }
  ])

  assert.equal(graph.nodes.length, 1)
  assert.equal(graph.nodes[0].title, 'department')
  assert.equal(graph.nodes[0].comment, '院系表')
  assert.deepEqual(
    graph.nodes[0].fields.map((field) => ({ name: field.name, primary: field.primary, required: field.required })),
    [
      { name: 'id', primary: true, required: true },
      { name: 'dept_name', primary: false, required: true }
    ]
  )
})

test('buildErGraph infers foreign-key style edges from xxx_id fields', () => {
  const graph = buildErGraph([
    {
      tableName: 'department',
      columns: [{ columnName: 'id', isPk: '1' }]
    },
    {
      tableName: 'student_info',
      columns: [
        { columnName: 'id', isPk: '1' },
        { columnName: 'department_id', columnComment: '所属院系' }
      ]
    }
  ])

  assert.equal(graph.edges.length, 1)
  assert.deepEqual(
    {
      source: graph.edges[0].source,
      target: graph.edges[0].target,
      fieldName: graph.edges[0].fieldName,
      targetFieldName: graph.edges[0].targetFieldName
    },
    {
      source: 'student_info',
      target: 'department',
      fieldName: 'department_id',
      targetFieldName: 'id'
    }
  )
})

test('buildErGraph applies saved node positions', () => {
  const graph = buildErGraph(
    [{ tableName: 'department', columns: [{ columnName: 'id', isPk: '1' }] }],
    { positions: { department: { x: 120, y: 240 } } }
  )

  assert.equal(graph.nodes[0].x, 120)
  assert.equal(graph.nodes[0].y, 240)
})

test('buildErGraph merges manual relations and hides deleted inferred relations', () => {
  const graph = buildErGraph(
    [
      { tableName: 'department', columns: [{ columnName: 'id', isPk: '1' }] },
      { tableName: 'student_info', columns: [{ columnName: 'id', isPk: '1' }, { columnName: 'department_id' }] },
      { tableName: 'class_info', columns: [{ columnName: 'id', isPk: '1' }] }
    ],
    {
      deletedEdgeIds: ['student_info.department_id->department.id'],
      relations: [
        {
          id: 'manual_student_class',
          source: 'student_info',
          target: 'class_info',
          fieldName: 'id',
          targetFieldName: 'id'
        }
      ]
    }
  )

  assert.equal(graph.edges.length, 1)
  assert.equal(graph.edges[0].id, 'manual_student_class')
  assert.equal(graph.edges[0].inferred, false)
})
