import { describe, expect, it, vi } from 'vitest'
import {
  decodeMuxFrame,
  encodeMuxFrame,
  encodeOpen,
  encodeGoaway,
  type MuxFrameHeader,
  type MuxOpen,
} from 'relay-contracts'
import { holdTunnel, dataHeader } from '../src/transport/tunnel.js'
import { FakeWs } from './fixtures/fakes.js'

const OPEN: MuxOpen = {
  streamId: 5,
  subdomain: 'host-42',
  requestPath: '/term?join=abc',
  originHeader: 'https://host-42.term.example.com',
  remoteAddrHash: 'deadbeef',
  capabilityTokenRef: 'jti-1',
}

function openFrame(open: MuxOpen): Uint8Array {
  const payload = encodeOpen(open)
  const header: MuxFrameHeader = {
    version: 1,
    type: 'open',
    fin: false,
    rst: false,
    streamId: open.streamId,
    payloadLen: payload.length,
  }
  return encodeMuxFrame(header, payload)
}

function stubHandlers() {
  return {
    handleOpen: vi.fn(),
    handleData: vi.fn(),
    handleClose: vi.fn(),
  }
}
const stubHb = { onPing: vi.fn(), onPong: vi.fn() }

describe('Tunnel (T7, §4.1)', () => {
  it('round-trips a frame and yields decoded header+payload via onFrame', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const seen: Array<{ h: MuxFrameHeader; p: Uint8Array }> = []
    tunnel.onFrame((h, p) => seen.push({ h, p }))
    ws.emitMessage(openFrame(OPEN))
    expect(seen).toHaveLength(1)
    expect(seen[0]!.h.type).toBe('open')
    expect(seen[0]!.h.streamId).toBe(5)
  })

  it('dispatches OPEN/DATA to the router', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const handlers = stubHandlers()
    tunnel.dispatchTo(handlers, stubHb)
    ws.emitMessage(openFrame(OPEN))
    expect(handlers.handleOpen).toHaveBeenCalledOnce()
    const data = new Uint8Array([1, 2, 3])
    ws.emitMessage(encodeMuxFrame(dataHeader(5, 3), data))
    expect(handlers.handleData).toHaveBeenCalledWith(5, expect.any(Uint8Array))
  })

  it('INV11: DATA payload passes through opaque (no parsing)', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const handlers = stubHandlers()
    tunnel.dispatchTo(handlers, stubHb)
    const opaque = new Uint8Array([0x1b, 0x5b, 0x33, 0x31, 0x6d]) // looks like an ANSI seq
    ws.emitMessage(encodeMuxFrame(dataHeader(7, opaque.length), opaque))
    const forwarded = handlers.handleData.mock.calls[0]![1] as Uint8Array
    expect(Buffer.from(forwarded).equals(Buffer.from(opaque))).toBe(true)
  })

  it('drains after inbound GOAWAY: no new OPEN accepted', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const handlers = stubHandlers()
    tunnel.dispatchTo(handlers, stubHb)
    const goaway = encodeGoaway(0, 'operatorDrain')
    ws.emitMessage(
      encodeMuxFrame(
        { version: 1, type: 'goaway', fin: false, rst: false, streamId: 0, payloadLen: goaway.length },
        goaway,
      ),
    )
    ws.emitMessage(openFrame({ ...OPEN, streamId: 9 }))
    expect(handlers.handleOpen).not.toHaveBeenCalled()
    // and it RST'd the refused stream
    const last = decodeMuxFrame(ws.sent.at(-1)!)
    expect(last.header.type).toBe('close')
    expect(last.header.rst).toBe(true)
  })

  it('malformed framing does not crash the tunnel', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    tunnel.dispatchTo(stubHandlers(), stubHb)
    expect(() => ws.emitMessage(new Uint8Array([0, 1, 2]))).not.toThrow()
  })

  it('dispatches CLOSE→handleClose and PONG→heartbeat.onPong', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const handlers = stubHandlers()
    const hb = { onPing: vi.fn(), onPong: vi.fn() }
    tunnel.dispatchTo(handlers, hb)
    ws.emitMessage(
      encodeMuxFrame({ version: 1, type: 'close', fin: false, rst: true, streamId: 5, payloadLen: 0 }, new Uint8Array(0)),
    )
    expect(handlers.handleClose).toHaveBeenCalledWith(5, true)
    ws.emitMessage(
      encodeMuxFrame({ version: 1, type: 'pong', fin: false, rst: false, streamId: 0, payloadLen: 2 }, new Uint8Array([1, 2])),
    )
    expect(hb.onPong).toHaveBeenCalledOnce()
  })

  it('send/goAway/sendRst/close emit well-formed frames', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    tunnel.send(dataHeader(3, 2), new Uint8Array([9, 9]))
    expect(decodeMuxFrame(ws.sent.at(-1)!).header.type).toBe('data')
    tunnel.goAway(3, 'shutdown')
    expect(decodeMuxFrame(ws.sent.at(-1)!).header.type).toBe('goaway')
    tunnel.sendRst(3)
    const rst = decodeMuxFrame(ws.sent.at(-1)!)
    expect(rst.header.type).toBe('close')
    expect(rst.header.rst).toBe(true)
    tunnel.close()
    expect(ws.closed).toBe(true)
  })

  it('windowUpdate frames are dispatched without disturbing the stream handlers', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const handlers = stubHandlers()
    tunnel.dispatchTo(handlers, stubHb)
    ws.emitMessage(
      encodeMuxFrame({ version: 1, type: 'windowUpdate', fin: false, rst: false, streamId: 1, payloadLen: 4 }, new Uint8Array([0, 0, 0, 5])),
    )
    expect(handlers.handleData).not.toHaveBeenCalled()
  })

  it('onGoAway surfaces the frozen reason', () => {
    const ws = new FakeWs()
    const tunnel = holdTunnel(ws)
    const reasons: string[] = []
    tunnel.onGoAway((r) => reasons.push(r))
    const goaway = encodeGoaway(3, 'revoked')
    ws.emitMessage(
      encodeMuxFrame(
        { version: 1, type: 'goaway', fin: false, rst: false, streamId: 0, payloadLen: goaway.length },
        goaway,
      ),
    )
    expect(reasons).toEqual(['revoked'])
  })
})
