-- Project-scoped chat threads: a ChatThread is now scoped to an Agent XOR a
-- Project. Existing rows are all agent-scoped, so dropping NOT NULL on agentId
-- is backward-compatible.

-- Agent link becomes optional; add the project link.
ALTER TABLE "ChatThread" ALTER COLUMN "agentId" DROP NOT NULL;
ALTER TABLE "ChatThread" ADD COLUMN "projectId" TEXT;

-- Exactly one of agentId / projectId must be set.
ALTER TABLE "ChatThread" ADD CONSTRAINT "ChatThread_agent_xor_project"
  CHECK ((("agentId" IS NOT NULL)::int + ("projectId" IS NOT NULL)::int) = 1);

-- Project FK (cascade delete threads with their project, mirroring the agent FK).
ALTER TABLE "ChatThread" ADD CONSTRAINT "ChatThread_projectId_fkey"
  FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE;

CREATE INDEX "ChatThread_projectId_lastTurnAt_idx" ON "ChatThread"("projectId", "lastTurnAt" DESC);
