ALTER TABLE "Lead"
  ADD COLUMN "wecomContactId" TEXT;

CREATE TABLE "WecomContactWay" (
  "id" TEXT NOT NULL,
  "configId" TEXT NOT NULL,
  "type" INTEGER NOT NULL DEFAULT 1,
  "scene" INTEGER NOT NULL DEFAULT 1,
  "style" INTEGER NOT NULL DEFAULT 1,
  "remark" TEXT,
  "state" TEXT,
  "wecomUserId" TEXT,
  "enabled" BOOLEAN NOT NULL DEFAULT true,
  "lastSyncedAt" TIMESTAMP(3),
  "lastSyncError" TEXT,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL,

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

CREATE TABLE "WecomExternalContact" (
  "id" TEXT NOT NULL,
  "externalUserId" TEXT NOT NULL,
  "wecomUserId" TEXT NOT NULL,
  "contactWayId" TEXT,
  "miniProgramUserId" TEXT,
  "customerId" TEXT,
  "name" TEXT,
  "avatarUrl" TEXT,
  "type" INTEGER,
  "gender" INTEGER,
  "unionId" TEXT,
  "corpName" TEXT,
  "position" TEXT,
  "remark" TEXT,
  "description" TEXT,
  "profile" JSONB,
  "status" TEXT NOT NULL DEFAULT 'active',
  "addedAt" TIMESTAMP(3),
  "lastEventAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "deletedAt" TIMESTAMP(3),
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL,

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

CREATE UNIQUE INDEX "WecomContactWay_configId_key" ON "WecomContactWay"("configId");
CREATE UNIQUE INDEX "WecomExternalContact_externalUserId_wecomUserId_key" ON "WecomExternalContact"("externalUserId", "wecomUserId");
CREATE INDEX "Lead_wecomContactId_idx" ON "Lead"("wecomContactId");
CREATE INDEX "WecomExternalContact_status_lastEventAt_idx" ON "WecomExternalContact"("status", "lastEventAt");
CREATE INDEX "WecomExternalContact_miniProgramUserId_idx" ON "WecomExternalContact"("miniProgramUserId");
CREATE INDEX "WecomExternalContact_customerId_idx" ON "WecomExternalContact"("customerId");
CREATE INDEX "WecomExternalContact_contactWayId_idx" ON "WecomExternalContact"("contactWayId");

ALTER TABLE "Lead"
  ADD CONSTRAINT "Lead_wecomContactId_fkey"
  FOREIGN KEY ("wecomContactId") REFERENCES "WecomExternalContact"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "WecomExternalContact"
  ADD CONSTRAINT "WecomExternalContact_contactWayId_fkey"
  FOREIGN KEY ("contactWayId") REFERENCES "WecomContactWay"("id") ON DELETE SET NULL ON UPDATE CASCADE,
  ADD CONSTRAINT "WecomExternalContact_miniProgramUserId_fkey"
  FOREIGN KEY ("miniProgramUserId") REFERENCES "MiniProgramUser"("id") ON DELETE SET NULL ON UPDATE CASCADE,
  ADD CONSTRAINT "WecomExternalContact_customerId_fkey"
  FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE SET NULL ON UPDATE CASCADE;
