import { describe, test, expect } from 'vitest'
import { extractSubdomain } from '../data-plane/subdomain-router.js'

const BASE = 'term.example.com'

describe('extractSubdomain (T7, INV1 Host-confusion guard)', () => {
  test('single-label tenant resolves to the leftmost label', () => {
    expect(extractSubdomain('alice.term.example.com', BASE)).toBe('alice')
  })

  test('bare base domain → null (no tenant)', () => {
    expect(extractSubdomain('term.example.com', BASE)).toBeNull()
  })

  test('suffix-confusion attempt → null', () => {
    expect(extractSubdomain('alice.term.example.com.evil.com', BASE)).toBeNull()
  })

  test('multi-label (nested) subdomain → null (single-label tenant only)', () => {
    expect(extractSubdomain('a.b.term.example.com', BASE)).toBeNull()
  })

  test('case-insensitive host', () => {
    expect(extractSubdomain('ALICE.Term.Example.COM', BASE)).toBe('alice')
  })

  test('trailing dot tolerated', () => {
    expect(extractSubdomain('alice.term.example.com.', BASE)).toBe('alice')
  })

  test('host:port suffix is stripped before matching', () => {
    expect(extractSubdomain('alice.term.example.com:8443', BASE)).toBe('alice')
  })

  test('invalid DNS label → null', () => {
    expect(extractSubdomain('_bad.term.example.com', BASE)).toBeNull()
  })
})
