import { AgentJobFragment, AgentStepFragment } from '../generated/schema'
import { error } from '../utils/error'

export interface Node {
	step: AgentStepFragment
	parents: Node[]
}

export interface Graph {
	job: AgentJobFragment
	nodes: Node[]
}

export module Graph {
	export function from(job: AgentJobFragment): Graph {
		const nodes = new Map<string, Node>(
			job.steps.map((step) => [
				step.id,
				{
					step,
					parents: [],
				},
			]),
		)

		for (const node of nodes.values()) {
			for (const dependency of node.step.dependencies) {
				const parent = nodes.get(dependency.id)

				if (parent) {
					node.parents.push(parent)
				}
			}
		}

		return {
			job,
			nodes: Array.from(nodes.values()),
		}
	}
}
