-- Migration: Eliminate plans table
-- Plans are now decompose tasks with parentTaskId for child relationships

PRAGMA foreign_keys=OFF;--> statement-breakpoint

-- Step 1: Create new tasks table with parent_task_id instead of plan_id
CREATE TABLE `__new_tasks` (
	`id` text PRIMARY KEY NOT NULL,
	`phase_id` text,
	`initiative_id` text,
	`parent_task_id` text,
	`name` text NOT NULL,
	`description` text,
	`type` text DEFAULT 'auto' NOT NULL,
	`category` text DEFAULT 'execute' NOT NULL,
	`priority` text DEFAULT 'medium' NOT NULL,
	`status` text DEFAULT 'pending' NOT NULL,
	`requires_approval` integer,
	`order` integer DEFAULT 0 NOT NULL,
	`created_at` integer NOT NULL,
	`updated_at` integer NOT NULL,
	FOREIGN KEY (`phase_id`) REFERENCES `phases`(`id`) ON UPDATE no action ON DELETE cascade,
	FOREIGN KEY (`initiative_id`) REFERENCES `initiatives`(`id`) ON UPDATE no action ON DELETE cascade,
	FOREIGN KEY (`parent_task_id`) REFERENCES `__new_tasks`(`id`) ON UPDATE no action ON DELETE cascade
);--> statement-breakpoint

-- Step 2: Insert plans as decompose tasks FIRST (so plan IDs exist as task IDs for foreign key)
INSERT INTO `__new_tasks`("id", "phase_id", "initiative_id", "parent_task_id", "name", "description", "type", "category", "priority", "status", "requires_approval", "order", "created_at", "updated_at")
SELECT
  "id",
  "phase_id",
  NULL,
  NULL,
  "name",
  "description",
  'auto',
  'decompose',
  'medium',
  CASE
    WHEN "status" = 'completed' THEN 'completed'
    WHEN "status" = 'in_progress' THEN 'in_progress'
    ELSE 'pending'
  END,
  NULL,
  "number",
  "created_at",
  "updated_at"
FROM `plans`;--> statement-breakpoint

-- Step 3: Copy existing tasks, converting plan_id to parent_task_id
INSERT INTO `__new_tasks`("id", "phase_id", "initiative_id", "parent_task_id", "name", "description", "type", "category", "priority", "status", "requires_approval", "order", "created_at", "updated_at")
SELECT "id", "phase_id", "initiative_id", "plan_id", "name", "description", "type", "category", "priority", "status", "requires_approval", "order", "created_at", "updated_at" FROM `tasks`;--> statement-breakpoint

-- Step 4: Drop old tasks table and rename new one
DROP TABLE `tasks`;--> statement-breakpoint
ALTER TABLE `__new_tasks` RENAME TO `tasks`;--> statement-breakpoint

-- Step 5: Drop plans table
DROP TABLE `plans`;--> statement-breakpoint

PRAGMA foreign_keys=ON;
