CREATE TYPE "MiniAppActivityType" AS ENUM (
  'SESSION_STARTED',
  'SCREEN_VIEWED',
  'SCREEN_TIME_RECORDED',
  'SERVICE_VIEWED',
  'SEARCH_USED',
  'FILTER_APPLIED',
  'CTA_CLICKED'
);

CREATE TABLE "MiniAppActivity" (
  "id" TEXT NOT NULL,
  "eventId" TEXT NOT NULL,
  "userId" TEXT NOT NULL,
  "sessionId" TEXT NOT NULL,
  "type" "MiniAppActivityType" NOT NULL,
  "screen" TEXT NOT NULL,
  "serviceId" TEXT,
  "serviceKind" TEXT,
  "label" TEXT,
  "destination" TEXT,
  "action" TEXT,
  "resultCount" INTEGER,
  "durationMs" INTEGER,
  "occurredAt" TIMESTAMP(3) NOT NULL,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE UNIQUE INDEX "MiniAppActivity_eventId_key"
  ON "MiniAppActivity"("eventId");
CREATE INDEX "MiniAppActivity_userId_occurredAt_idx"
  ON "MiniAppActivity"("userId", "occurredAt");
CREATE INDEX "MiniAppActivity_type_occurredAt_idx"
  ON "MiniAppActivity"("type", "occurredAt");
CREATE INDEX "MiniAppActivity_screen_occurredAt_idx"
  ON "MiniAppActivity"("screen", "occurredAt");
CREATE INDEX "MiniAppActivity_sessionId_occurredAt_idx"
  ON "MiniAppActivity"("sessionId", "occurredAt");
CREATE INDEX "MiniAppActivity_serviceId_occurredAt_idx"
  ON "MiniAppActivity"("serviceId", "occurredAt");

ALTER TABLE "MiniAppActivity"
  ADD CONSTRAINT "MiniAppActivity_userId_fkey"
  FOREIGN KEY ("userId") REFERENCES "TelegramUser"("id")
  ON DELETE CASCADE ON UPDATE CASCADE;
