-- Add agent-direct prompts and per-agent personalities (with personality<->prompt join).

-- ── Prompt: optional agentId, mirrors projectId pattern ──
ALTER TABLE "Prompt" ADD COLUMN "agentId" TEXT;

CREATE UNIQUE INDEX "Prompt_name_agentId_key" ON "Prompt"("name", "agentId");
CREATE INDEX "Prompt_agentId_idx" ON "Prompt"("agentId");

ALTER TABLE "Prompt" ADD CONSTRAINT "Prompt_agentId_fkey"
  FOREIGN KEY ("agentId") REFERENCES "Agent"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- ── Agent: defaultPersonalityId (optional FK; SET NULL on delete to keep agent alive) ──
ALTER TABLE "Agent" ADD COLUMN "defaultPersonalityId" TEXT;

CREATE INDEX "Agent_defaultPersonalityId_idx" ON "Agent"("defaultPersonalityId");

-- ── Personality table ──
CREATE TABLE "Personality" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "description" TEXT NOT NULL DEFAULT '',
    "agentId" TEXT NOT NULL,
    "priority" INTEGER NOT NULL DEFAULT 5,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "Personality_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "Personality_name_agentId_key" ON "Personality"("name", "agentId");
CREATE INDEX "Personality_agentId_idx" ON "Personality"("agentId");

ALTER TABLE "Personality" ADD CONSTRAINT "Personality_agentId_fkey"
  FOREIGN KEY ("agentId") REFERENCES "Agent"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- Now that Personality exists, the Agent.defaultPersonalityId FK can point at it.
ALTER TABLE "Agent" ADD CONSTRAINT "Agent_defaultPersonalityId_fkey"
  FOREIGN KEY ("defaultPersonalityId") REFERENCES "Personality"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- ── PersonalityPrompt join table ──
CREATE TABLE "PersonalityPrompt" (
    "id" TEXT NOT NULL,
    "personalityId" TEXT NOT NULL,
    "promptId" TEXT NOT NULL,
    "priority" INTEGER NOT NULL DEFAULT 5,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "PersonalityPrompt_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "PersonalityPrompt_personalityId_promptId_key" ON "PersonalityPrompt"("personalityId", "promptId");
CREATE INDEX "PersonalityPrompt_personalityId_idx" ON "PersonalityPrompt"("personalityId");
CREATE INDEX "PersonalityPrompt_promptId_idx" ON "PersonalityPrompt"("promptId");

ALTER TABLE "PersonalityPrompt" ADD CONSTRAINT "PersonalityPrompt_personalityId_fkey"
  FOREIGN KEY ("personalityId") REFERENCES "Personality"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "PersonalityPrompt" ADD CONSTRAINT "PersonalityPrompt_promptId_fkey"
  FOREIGN KEY ("promptId") REFERENCES "Prompt"("id") ON DELETE CASCADE ON UPDATE CASCADE;
