import { computed, inject, provide, unref, type ComputedRef, type InjectionKey, type MaybeRef } from 'vue'

import type { IWorkflow } from '../Interface'

export interface WorkflowContext {
	workflow: ComputedRef<IWorkflow | undefined>
}

const workflowContextKey: InjectionKey<WorkflowContext> = Symbol('workflow-context')

export function provideWorkflowContext(workflow: MaybeRef<IWorkflow | undefined>): WorkflowContext {
	const context: WorkflowContext = {
		workflow: computed(() => unref(workflow))
	}

	provide(workflowContextKey, context)

	return context
}

export function useWorkflowContext(): WorkflowContext {
	const context = inject(workflowContextKey, null)

	if (!context) {
		throw new Error('useWorkflowContext must be used within Workflow')
	}

	return context
}
