-- Add ownerId column to tasks table
ALTER TABLE "tasks" ADD COLUMN "ownerId" TEXT NOT NULL DEFAULT '';

-- Get the first user ID to assign all existing tasks
-- We'll use a subquery to get the first user's ID
UPDATE "tasks" 
SET "ownerId" = (
    SELECT "id" FROM "users" 
    ORDER BY "createdAt" ASC 
    LIMIT 1
)
WHERE "ownerId" = '';

-- Now make ownerId NOT NULL without default
-- First, we need to recreate the table since SQLite doesn't support ALTER COLUMN
CREATE TABLE "tasks_new" (
    "id" TEXT NOT NULL PRIMARY KEY,
    "title" TEXT NOT NULL,
    "description" TEXT,
    "status" TEXT NOT NULL DEFAULT 'todo',
    "priority" TEXT NOT NULL DEFAULT 'medium',
    "source" TEXT NOT NULL,
    "sourceId" TEXT,
    "dueDate" DATETIME,
    "completedAt" DATETIME,
    "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" DATETIME NOT NULL,
    "jiraProject" TEXT,
    "jiraKey" TEXT,
    "assignee" TEXT,
    "ownerId" TEXT NOT NULL,
    "jiraType" TEXT,
    "tfsProject" TEXT,
    "tfsPullRequestId" INTEGER,
    "tfsRepository" TEXT,
    "tfsSourceBranch" TEXT,
    "tfsTargetBranch" TEXT,
    "primaryTagId" TEXT,
    CONSTRAINT "tasks_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT "tasks_primaryTagId_fkey" FOREIGN KEY ("primaryTagId") REFERENCES "tags" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);

-- Copy data from old table to new table
INSERT INTO "tasks_new" SELECT * FROM "tasks";

-- Drop old table
DROP TABLE "tasks";

-- Rename new table
ALTER TABLE "tasks_new" RENAME TO "tasks";

-- Recreate indexes
CREATE UNIQUE INDEX "tasks_source_sourceId_key" ON "tasks"("source", "sourceId");
CREATE INDEX "tasks_ownerId_idx" ON "tasks"("ownerId");
