-- Agent-side support: human (store admin) replies into escalated sessions.
--
-- Apply manually against CHAT_DATABASE_URL, like 001/002:
--   psql "$CHAT_DATABASE_URL" -f chat-service/prisma/migrations/manual/003_agent_support.sql
--
-- NOTE: ALTER TYPE ... ADD VALUE cannot run inside a transaction block.
-- psql runs each statement in its own implicit transaction by default, which
-- is fine — just don't wrap this file in BEGIN/COMMIT.

-- Messages written by a human agent, distinct from the bot's 'assistant'
-- role so the widget can label them and the bot pipeline can ignore them.
ALTER TYPE "chat"."ChatMessageRole" ADD VALUE IF NOT EXISTS 'agent';

-- Maps a chat application to the store it serves in the cart platform.
-- This is the escalation-routing rule: a store admin's JWT carries their
-- storeId, and they act as agent for the application matching it.
ALTER TABLE "chat"."applications"
  ADD COLUMN IF NOT EXISTS "external_store_id" TEXT;

CREATE UNIQUE INDEX IF NOT EXISTS "applications_external_store_id_key"
  ON "chat"."applications" ("external_store_id")
  WHERE "external_store_id" IS NOT NULL;
