/**
 * test/desktop/deep-link.test.ts — B2: parseDeepLink / deepLinkToPath.
 */

import { describe, test, expect } from 'vitest'
import {
  DEEP_LINK_PROTOCOL,
  parseDeepLink,
  deepLinkToPath,
} from '../../desktop/src/deep-link.js'

describe('DEEP_LINK_PROTOCOL', () => {
  test('is the terminalapp scheme', () => {
    expect(DEEP_LINK_PROTOCOL).toBe('terminalapp')
  })
})

describe('parseDeepLink', () => {
  test('parses a valid terminalapp://join/<id> link', () => {
    // Arrange
    const url = 'terminalapp://join/abc123'

    // Act
    const result = parseDeepLink(url)

    // Assert
    expect(result).toEqual({ join: 'abc123' })
  })

  test('decodes a percent-encoded id', () => {
    // Arrange
    const url = 'terminalapp://join/a%20b'

    // Act
    const result = parseDeepLink(url)

    // Assert
    expect(result).toEqual({ join: 'a b' })
  })

  test('returns null for a wrong scheme', () => {
    expect(parseDeepLink('https://join/abc')).toBeNull()
  })

  test('returns null for a wrong host', () => {
    expect(parseDeepLink('terminalapp://open/abc')).toBeNull()
  })

  test('returns null when the id is missing', () => {
    expect(parseDeepLink('terminalapp://join')).toBeNull()
    expect(parseDeepLink('terminalapp://join/')).toBeNull()
  })

  test('returns null when the id contains a nested slash', () => {
    expect(parseDeepLink('terminalapp://join/a/b')).toBeNull()
  })

  test('returns null for a whitespace-only id', () => {
    expect(parseDeepLink('terminalapp://join/%20')).toBeNull()
  })

  test('returns null for an id with a control character', () => {
    expect(parseDeepLink('terminalapp://join/a%01b')).toBeNull()
  })

  test('returns null for malformed percent-encoding', () => {
    expect(parseDeepLink('terminalapp://join/%E0%A4%A')).toBeNull()
  })

  test('returns null for a malformed URL', () => {
    expect(parseDeepLink('not a url')).toBeNull()
    expect(parseDeepLink('')).toBeNull()
  })
})

describe('deepLinkToPath', () => {
  test('renders the /?join= route for a simple id', () => {
    expect(deepLinkToPath({ join: 'abc123' })).toBe('/?join=abc123')
  })

  test('encodes an id needing escaping', () => {
    expect(deepLinkToPath({ join: 'a b/c' })).toBe('/?join=a%20b%2Fc')
  })

  test('round-trips a percent-decoded id back through encoding', () => {
    // Arrange
    const parsed = parseDeepLink('terminalapp://join/a%20b')
    expect(parsed).not.toBeNull()

    // Act
    const path = deepLinkToPath(parsed!)

    // Assert
    expect(path).toBe('/?join=a%20b')
  })
})
