-- Workflows: pipeline definitions
CREATE TABLE `workflows` (
	`id` int AUTO_INCREMENT NOT NULL,
	`name` varchar(255) NOT NULL,
	`description` text,
	`status` enum('draft','active','paused','archived') NOT NULL DEFAULT 'draft',
	`canvasMeta` json DEFAULT ('{}'),
	`tags` json DEFAULT ('[]'),
	`createdBy` int,
	`createdAt` timestamp NOT NULL DEFAULT (now()),
	`updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `workflows_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint

-- Workflow Nodes: blocks inside a workflow (agent / container / trigger / condition / output)
CREATE TABLE `workflowNodes` (
	`id` int AUTO_INCREMENT NOT NULL,
	`workflowId` int NOT NULL,
	`nodeKey` varchar(64) NOT NULL,
	`label` varchar(255) NOT NULL,
	`kind` enum('agent','container','trigger','condition','output') NOT NULL,
	`agentId` int,
	`containerConfig` json DEFAULT ('{}'),
	`conditionExpr` text,
	`triggerConfig` json DEFAULT ('{}'),
	`posX` int DEFAULT 0,
	`posY` int DEFAULT 0,
	`meta` json DEFAULT ('{}'),
	`createdAt` timestamp NOT NULL DEFAULT (now()),
	`updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `workflowNodes_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
CREATE INDEX `workflowNodes_workflowId_idx` ON `workflowNodes` (`workflowId`);
--> statement-breakpoint

-- Workflow Edges: connections between nodes
CREATE TABLE `workflowEdges` (
	`id` int AUTO_INCREMENT NOT NULL,
	`workflowId` int NOT NULL,
	`edgeKey` varchar(64) NOT NULL,
	`sourceNodeKey` varchar(64) NOT NULL,
	`targetNodeKey` varchar(64) NOT NULL,
	`sourceHandle` varchar(64),
	`targetHandle` varchar(64),
	`label` varchar(128),
	`meta` json DEFAULT ('{}'),
	`createdAt` timestamp NOT NULL DEFAULT (now()),
	CONSTRAINT `workflowEdges_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
CREATE INDEX `workflowEdges_workflowId_idx` ON `workflowEdges` (`workflowId`);
--> statement-breakpoint

-- Workflow Runs: execution history with per-node results
CREATE TABLE `workflowRuns` (
	`id` int AUTO_INCREMENT NOT NULL,
	`workflowId` int NOT NULL,
	`runKey` varchar(64) NOT NULL,
	`status` enum('pending','running','success','failed','cancelled') NOT NULL DEFAULT 'pending',
	`nodeResults` json DEFAULT ('{}'),
	`currentNodeKey` varchar(64),
	`input` text,
	`output` text,
	`totalDurationMs` int,
	`errorMessage` text,
	`startedAt` timestamp,
	`finishedAt` timestamp,
	`createdAt` timestamp NOT NULL DEFAULT (now()),
	CONSTRAINT `workflowRuns_id` PRIMARY KEY(`id`),
	CONSTRAINT `workflowRuns_runKey_unique` UNIQUE(`runKey`)
);
--> statement-breakpoint
CREATE INDEX `workflowRuns_workflowId_idx` ON `workflowRuns` (`workflowId`);
--> statement-breakpoint
CREATE INDEX `workflowRuns_status_idx` ON `workflowRuns` (`status`);
