import { describe, expect, it } from 'vitest'
import { ensureAllowedOrigin, subdomainOrigin, type OriginFsDeps } from '../src/service/originConfig.js'

function memFs(initial: string | null): { fs: OriginFsDeps; get(): string } {
  const store = { content: initial }
  const fs: OriginFsDeps = {
    exists: () => store.content !== null,
    read: () => store.content ?? '',
    write: (_p, c) => {
      store.content = c
    },
  }
  return { fs, get: () => store.content ?? '' }
}

const PATH = '/etc/web-terminal.env'

describe('ensureAllowedOrigin (T17, EXPLORE §3)', () => {
  it('composes https://<subdomain>.term.<domain>', () => {
    expect(subdomainOrigin('host-42', 'example.com')).toBe('https://host-42.term.example.com')
  })

  it('appends the origin when the file has none', () => {
    const { fs, get } = memFs('PORT=3000\n')
    ensureAllowedOrigin(PATH, 'host-42', 'example.com', fs)
    expect(get()).toContain('ALLOWED_ORIGINS=https://host-42.term.example.com')
    expect(get()).toContain('PORT=3000')
  })

  it('is idempotent (no duplicate on a second run)', () => {
    const { fs, get } = memFs('ALLOWED_ORIGINS=https://host-42.term.example.com\n')
    ensureAllowedOrigin(PATH, 'host-42', 'example.com', fs)
    const matches = get().match(/host-42\.term\.example\.com/g) ?? []
    expect(matches).toHaveLength(1)
  })

  it('preserves existing origins (never weakens the Origin check)', () => {
    const { fs, get } = memFs('ALLOWED_ORIGINS=https://existing.example.com\n')
    ensureAllowedOrigin(PATH, 'host-42', 'example.com', fs)
    expect(get()).toContain('https://existing.example.com')
    expect(get()).toContain('https://host-42.term.example.com')
  })
})
