import { describe, expect, test } from 'bun:test'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { createRfwtxtMiddleware } from './middleware.ts'

const CUSTOMER_WORKFLOWS = '/home/mmack/workspace/pyck-projects/customer-template/workflows'

function createMockReqRes(url: string) {
	let statusCode = 200
	let body = ''
	const headers: Record<string, string> = {}

	const req = { url, headers: { accept: '*/*' } } as unknown as IncomingMessage

	const res = {
		get statusCode() {
			return statusCode
		},
		set statusCode(code: number) {
			statusCode = code
		},
		setHeader(name: string, value: string) {
			headers[name] = value
		},
		end(data?: string | Buffer) {
			body = typeof data === 'string' ? data : (data?.toString('utf-8') ?? '')
		},
	} as unknown as ServerResponse

	return { req, res, getStatus: () => statusCode, getBody: () => body, getHeaders: () => headers }
}

describe('createRfwtxtMiddleware', () => {
	const middleware = createRfwtxtMiddleware(CUSTOMER_WORKFLOWS)

	test('passes through non-rfwtxt requests', () => {
		const { req, res } = createMockReqRes('/some/other/path')
		let nextCalled = false
		middleware(req, res, () => {
			nextCalled = true
		})
		expect(nextCalled).toBe(true)
	})

	test('passes through non-mobile requests', () => {
		const { req, res } = createMockReqRes('/workflows/test.rfwtxt')
		let nextCalled = false
		middleware(req, res, () => {
			nextCalled = true
		})
		expect(nextCalled).toBe(true)
	})

	test('returns 404 for non-existent rfwtxt file', () => {
		const { req, res, getStatus } = createMockReqRes(
			'/mobile/workflows/999-nonexistent/mobile/nope.rfwtxt',
		)
		middleware(req, res, () => {})
		expect(getStatus()).toBe(404)
	})

	test('blocks path traversal attempts', () => {
		const { req, res, getStatus } = createMockReqRes('/mobile/workflows/../../etc/passwd.rfwtxt')
		middleware(req, res, () => {})
		// Should be either 403 (traversal detected) or 404 (file not found)
		expect(getStatus()).toBeGreaterThanOrEqual(403)
	})
})
