CREATE TABLE `agents` (
	`id` varchar(36) NOT NULL,
	`pod_name` varchar(253) NOT NULL,
	`k8s_namespace` varchar(63) DEFAULT 'agents',
	`status` enum('idle','busy','error','offline') DEFAULT 'idle',
	`current_task_id` varchar(36),
	`tasks_completed` int DEFAULT 0,
	`last_heartbeat` timestamp,
	`created_at` timestamp DEFAULT (now()),
	`updated_at` timestamp DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `agents_id` PRIMARY KEY(`id`),
	CONSTRAINT `agents_pod_name_unique` UNIQUE(`pod_name`)
);
--> statement-breakpoint
CREATE TABLE `projects` (
	`id` varchar(36) NOT NULL,
	`name` varchar(255) NOT NULL,
	`description` text,
	`gitea_repo_id` int,
	`gitea_repo_url` varchar(512),
	`gitea_owner` varchar(100),
	`gitea_repo_name` varchar(100),
	`default_branch` varchar(100) DEFAULT 'main',
	`k8s_namespace` varchar(63) NOT NULL,
	`docker_image` varchar(512),
	`env_vars` json,
	`replicas` int DEFAULT 1,
	`cpu_limit` varchar(20) DEFAULT '500m',
	`memory_limit` varchar(20) DEFAULT '512Mi',
	`status` enum('active','paused','archived') DEFAULT 'active',
	`created_at` timestamp DEFAULT (now()),
	`updated_at` timestamp DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `projects_id` PRIMARY KEY(`id`),
	CONSTRAINT `projects_k8s_namespace_unique` UNIQUE(`k8s_namespace`)
);
--> statement-breakpoint
CREATE TABLE `tasks` (
	`id` varchar(36) NOT NULL,
	`project_id` varchar(36) NOT NULL,
	`title` varchar(255) NOT NULL,
	`description` text,
	`priority` enum('low','medium','high','urgent') DEFAULT 'medium',
	`state` enum('backlog','in_progress','needs_input','ready_to_test','approved','staging','production') DEFAULT 'backlog',
	`assigned_agent_id` varchar(36),
	`branch_name` varchar(255),
	`pr_url` varchar(512),
	`preview_url` varchar(512),
	`created_at` timestamp DEFAULT (now()),
	`updated_at` timestamp DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `tasks_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
ALTER TABLE `tasks` ADD CONSTRAINT `tasks_project_id_projects_id_fk` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `tasks` ADD CONSTRAINT `tasks_assigned_agent_id_agents_id_fk` FOREIGN KEY (`assigned_agent_id`) REFERENCES `agents`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX `idx_status` ON `agents` (`status`);--> statement-breakpoint
CREATE INDEX `idx_status` ON `projects` (`status`);--> statement-breakpoint
CREATE INDEX `idx_project_state` ON `tasks` (`project_id`,`state`);