import { describe, expect, it } from 'vitest'

import remarkWikiAutolink from '@/lib/remark-wiki-autolink'

import type { Root } from 'mdast'

describe ('remarkWikiAutolink', () => {
  it ('links matching wiki page names and prefers longer matches', () => {
    const tree: Root = {
      type:     'root',
      children: [{
        type:     'paragraph',
        children: [{ type: 'text', value: '虹夏 and 虹' }],
      }],
    }

    remarkWikiAutolink (['虹', '虹夏']) (tree)

    expect (tree.children[0]).toMatchObject ({
      type:     'paragraph',
      children: [
        {
          type:     'link',
          url:      '/wiki/%E8%99%B9%E5%A4%8F',
          children: [{ type: 'text', value: '虹夏' }],
        },
        { type: 'text', value: ' and ' },
        {
          type:     'link',
          url:      '/wiki/%E8%99%B9',
          children: [{ type: 'text', value: '虹' }],
        },
      ],
    })
  })

  it ('does not link text inside existing links or code', () => {
    const tree: Root = {
      type:     'root',
      children: [
        {
          type:     'paragraph',
          children: [{
            type:     'link',
            url:      '/existing',
            children: [{ type: 'text', value: '虹' }],
          }],
        },
        {
          type:  'code',
          value: '虹',
        },
      ],
    }

    remarkWikiAutolink (['虹']) (tree)

    expect (tree.children[0]).toMatchObject ({
      type:     'paragraph',
      children: [{
        type:     'link',
        url:      '/existing',
        children: [{ type: 'text', value: '虹' }],
      }],
    })
    expect (tree.children[1]).toMatchObject ({ type: 'code', value: '虹' })
  })
})
