import { formatLink } from 'src/lib/url-format'

describe('formatLink', () => {
  test.each([
    ['https://www.example.com/', { display: 'example.com', host: 'example.com' }],
    [
      'https://www.example.com/foo/bar',
      { display: 'example.com/foo/bar', host: 'example.com' },
    ],
    [
      'https://www.example.com/foo/bar?utm=x#sec',
      { display: 'example.com/foo/bar', host: 'example.com' },
    ],
    [
      'https://en.wikipedia.org/wiki/Primer_(film)',
      {
        display: 'en.wikipedia.org/wiki/Primer_(film)',
        host: 'en.wikipedia.org',
      },
    ],
    [
      'https://youtube.com/watch?v=dQw4w9WgXcQ',
      { display: 'youtube.com/watch', host: 'youtube.com' },
    ],
    ['https://localhost:3000/foo', { display: 'localhost:3000/foo', host: 'localhost' }],
    ['http://1.2.3.4:8080/foo', { display: '1.2.3.4:8080/foo', host: '1.2.3.4' }],
    [
      'https://xn--r8jz45g.jp/foo',
      { display: 'xn--r8jz45g.jp/foo', host: 'xn--r8jz45g.jp' },
    ],
  ])('formats %s', (url, expected) => {
    const result = formatLink(url)
    expect(result?.display).toBe(expected.display)
    expect(result?.host).toBe(expected.host)
    expect(result?.href).toBe(url)
  })

  test('long path ellipsizes at 30 chars', () => {
    const result = formatLink('https://example.com/very/long/path/here/that/keeps/going')
    expect(result?.display).toMatch(/^example\.com\/.{1,30}…$/)
    // host (`example.com`) + max 30 path chars + `…` (1 char in JS).
    expect(result?.display.length).toBeLessThanOrEqual('example.com'.length + 31)
  })

  test('garbage returns null', () => {
    expect(formatLink('not a url')).toBeNull()
    expect(formatLink('javascript:alert(1)')).toBeNull()
    expect(formatLink('mailto:foo@bar')).toBeNull()
  })

  test('href is preserved verbatim', () => {
    const url = 'https://www.example.com/foo/bar?utm=x#sec'
    expect(formatLink(url)?.href).toBe(url)
  })
})
