import type { Plugin } from 'vite'

/**
 * Vite plugin that ensures bare-specifier imports from workflow files
 * (e.g. `react`, `@pyck/react`, `@pyck/styled-system`) resolve through
 * the project's node_modules instead of potentially finding duplicates.
 *
 * Without this, workflow files living outside the Vite root would fail
 * to resolve deps or — worse — load a second copy of React.
 *
 * Based on Chris's original resolve-workflows-deps plugin from customer-template/web/.
 */
export function resolveWorkflowsDeps(resolveFromPath: string): Plugin {
	return {
		name: 'resolve-workflows-deps',
		enforce: 'pre',
		resolveId: {
			order: 'pre',
			async handler(source, importer, options) {
				// Only intercept imports originating from workflow files.
				if (!importer?.includes('/workflows/')) return

				// Skip relative and absolute imports — they resolve fine on their own.
				if (source.startsWith('.') || source.startsWith('/')) return

				// Re-resolve the bare specifier as if it were imported from the
				// project root. This forces Node resolution to walk up from the
				// project's node_modules, guaranteeing a single shared copy.
				const resolved = await this.resolve(source, resolveFromPath, {
					...options,
					skipSelf: true,
				})
				return resolved
			},
		},
	}
}
