-- M1-step2/3/4: Memory 三个正交维度
--   ownerScope  USER | ORG     —— 归属（用户私有 / 全 org 共享）
--   scope       GLOBAL | PROJECT | PERSONA  —— 已存在
--   category    USER | FEEDBACK | PROJECT | REFERENCE  —— 借鉴 CC/OC 四分类
-- + AgentSession.personaId （session 绑 persona，激活 PERSONA-scope 注入）

-- CreateEnum
CREATE TYPE "platform_ai"."MemoryOwnerScope" AS ENUM ('USER', 'ORG');

-- CreateEnum
CREATE TYPE "platform_ai"."MemoryCategory" AS ENUM ('USER', 'FEEDBACK', 'PROJECT', 'REFERENCE');

-- AlterTable: agent_memories 加 ownerScope / category + createdById 改 nullable
ALTER TABLE "platform_ai"."agent_memories"
  ADD COLUMN "category"   "platform_ai"."MemoryCategory"   NOT NULL DEFAULT 'USER',
  ADD COLUMN "ownerScope" "platform_ai"."MemoryOwnerScope" NOT NULL DEFAULT 'USER',
  ALTER COLUMN "createdById" DROP NOT NULL;

-- AlterTable: agent_sessions 加 personaId
ALTER TABLE "platform_ai"."agent_sessions" ADD COLUMN "personaId" UUID;

-- CreateIndex
CREATE INDEX "agent_memories_organizationId_ownerScope_scope_updatedAt_idx"
  ON "platform_ai"."agent_memories"("organizationId", "ownerScope", "scope", "updatedAt" DESC);

-- CreateIndex
CREATE INDEX "agent_sessions_personaId_idx" ON "platform_ai"."agent_sessions"("personaId");

-- AddForeignKey
ALTER TABLE "platform_ai"."agent_sessions"
  ADD CONSTRAINT "agent_sessions_personaId_fkey"
  FOREIGN KEY ("personaId") REFERENCES "platform_ai"."agent_personas"("id")
  ON DELETE SET NULL ON UPDATE CASCADE;

-- Application-layer 约束（DB 层补强）：ownerScope=USER 必须有 createdById；ownerScope=ORG 必须无 createdById
ALTER TABLE "platform_ai"."agent_memories"
  ADD CONSTRAINT "agent_memories_owner_consistency"
  CHECK (
    ("ownerScope" = 'USER' AND "createdById" IS NOT NULL) OR
    ("ownerScope" = 'ORG'  AND "createdById" IS NULL)
  );
