-- Chat sessions and messages for iterative phase/task refinement
CREATE TABLE `chat_sessions` (
	`id` text PRIMARY KEY NOT NULL,
	`target_type` text NOT NULL,
	`target_id` text NOT NULL,
	`initiative_id` text NOT NULL REFERENCES `initiatives`(`id`) ON DELETE CASCADE,
	`agent_id` text REFERENCES `agents`(`id`) ON DELETE SET NULL,
	`status` text DEFAULT 'active' NOT NULL,
	`created_at` integer NOT NULL,
	`updated_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `chat_sessions_target_idx` ON `chat_sessions` (`target_type`, `target_id`);
--> statement-breakpoint
CREATE INDEX `chat_sessions_initiative_id_idx` ON `chat_sessions` (`initiative_id`);
--> statement-breakpoint
CREATE TABLE `chat_messages` (
	`id` text PRIMARY KEY NOT NULL,
	`chat_session_id` text NOT NULL REFERENCES `chat_sessions`(`id`) ON DELETE CASCADE,
	`role` text NOT NULL,
	`content` text NOT NULL,
	`change_set_id` text REFERENCES `change_sets`(`id`) ON DELETE SET NULL,
	`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `chat_messages_session_id_idx` ON `chat_messages` (`chat_session_id`);
