import { describe, expect, test } from 'bun:test'
import path from 'node:path'
import { discoverExposes, discoverWorkflows } from './discover.ts'

// These tests use a local fixture directory that matches the expected
// web/ and mobile/ naming convention.
const FIXTURE_DIR = path.resolve(import.meta.dirname, '__fixtures__', 'workflows')

describe('discoverWorkflows', () => {
	test('discovers web entries', () => {
		const entries = discoverWorkflows(FIXTURE_DIR)
		const webEntries = entries.filter((e) => e.platform === 'web')

		expect(webEntries.length).toBe(2)

		const verifyItem = webEntries.find((e) => e.task === 'verify-item-details')
		expect(verifyItem).toBeDefined()
		expect(verifyItem?.workflow).toBe('001-test')
		expect(verifyItem?.platform).toBe('web')
		expect(verifyItem?.filePath).toEndWith('/web/verify-item-details/main.tsx')
	})

	test('discovers mobile entries', () => {
		const entries = discoverWorkflows(FIXTURE_DIR)
		const mobileEntries = entries.filter((e) => e.platform === 'mobile')

		expect(mobileEntries.length).toBe(1)
		expect(mobileEntries[0].task).toBe('verify-item-details')
		expect(mobileEntries[0].workflow).toBe('001-test')
	})

	test('returns empty array for non-existent directory', () => {
		const entries = discoverWorkflows('/non/existent/path')
		expect(entries).toEqual([])
	})

	test('entry filePaths are absolute', () => {
		const entries = discoverWorkflows(FIXTURE_DIR)
		for (const entry of entries) {
			expect(path.isAbsolute(entry.filePath)).toBe(true)
		}
	})
})

describe('discoverExposes', () => {
	test('creates correct MF expose map', () => {
		const exposes = discoverExposes(FIXTURE_DIR)

		expect(Object.keys(exposes).length).toBe(2)
		expect(exposes['./001-test/verify-item-details']).toBeDefined()
		expect(exposes['./001-test/confirm-action']).toBeDefined()

		for (const filePath of Object.values(exposes)) {
			expect(path.isAbsolute(filePath)).toBe(true)
			expect(filePath).toEndWith('/main.tsx')
		}
	})

	test('returns empty object for non-existent directory', () => {
		const exposes = discoverExposes('/non/existent/path')
		expect(exposes).toEqual({})
	})
})
