-- Real product usage telemetry for Phase One mobile and dashboard loops.

CREATE TABLE "EngagementEvent" (
    "id" TEXT NOT NULL,
    "userId" TEXT,
    "sessionId" TEXT,
    "eventType" TEXT NOT NULL,
    "screen" TEXT,
    "entityType" TEXT,
    "entityId" TEXT,
    "query" TEXT,
    "metadata" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE INDEX "EngagementEvent_userId_createdAt_idx" ON "EngagementEvent"("userId", "createdAt");
CREATE INDEX "EngagementEvent_eventType_createdAt_idx" ON "EngagementEvent"("eventType", "createdAt");
CREATE INDEX "EngagementEvent_entityType_entityId_idx" ON "EngagementEvent"("entityType", "entityId");
CREATE INDEX "EngagementEvent_query_idx" ON "EngagementEvent"("query");

ALTER TABLE "EngagementEvent"
ADD CONSTRAINT "EngagementEvent_userId_fkey"
FOREIGN KEY ("userId") REFERENCES "User"("id")
ON DELETE SET NULL ON UPDATE CASCADE;
