-- Success-sharing milestones. Run once against the target database before
-- deploying the application version that uses this feature.
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "xHandle" TEXT;
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "socialPromptOptOut" BOOLEAN NOT NULL DEFAULT false;

CREATE TABLE IF NOT EXISTS "SocialMilestone" (
  "id" TEXT PRIMARY KEY,
  "qrId" TEXT NOT NULL REFERENCES "QRCode"("id") ON DELETE CASCADE,
  "userId" TEXT NOT NULL REFERENCES "User"("id") ON DELETE CASCADE,
  "kind" TEXT NOT NULL,
  "status" TEXT NOT NULL DEFAULT 'detected',
  "detectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "shownAt" TIMESTAMP(3),
  "respondedAt" TIMESTAMP(3),
  "postedAt" TIMESTAMP(3),
  "withName" BOOLEAN NOT NULL DEFAULT false,
  "consentText" TEXT,
  CONSTRAINT "SocialMilestone_qr_kind_key" UNIQUE ("qrId", "kind")
);

CREATE INDEX IF NOT EXISTS "SocialMilestone_status_respondedAt_idx"
  ON "SocialMilestone" ("status", "respondedAt");
CREATE INDEX IF NOT EXISTS "SocialMilestone_userId_status_idx"
  ON "SocialMilestone" ("userId", "status");

ALTER TABLE "SocialMilestone" ADD COLUMN IF NOT EXISTS "claimedAt" TIMESTAMP(3);
ALTER TABLE "SocialMilestone" ADD COLUMN IF NOT EXISTS "language" TEXT NOT NULL DEFAULT 'en';
ALTER TABLE "SocialMilestone" ADD COLUMN IF NOT EXISTS "cardData" JSONB;
CREATE INDEX IF NOT EXISTS "SocialMilestone_status_claimedAt_idx"
  ON "SocialMilestone" ("status", "claimedAt");
