-- ADR-0024 / Issue 44: Feishu provider-local user identifiers are scoped by
-- the Organization's stable customer application connection. Existing legacy
-- User.feishuOpenId values are deliberately not guessed into this table.

CREATE TABLE "FeishuUserIdentity" (
    "id" TEXT NOT NULL,
    "connectionId" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "openId" TEXT NOT NULL,
    "unionId" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "FeishuUserIdentity_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "FeishuUserIdentity_connectionId_openId_key"
  ON "FeishuUserIdentity"("connectionId", "openId");
CREATE UNIQUE INDEX "FeishuUserIdentity_connectionId_unionId_key"
  ON "FeishuUserIdentity"("connectionId", "unionId");
CREATE UNIQUE INDEX "FeishuUserIdentity_connectionId_userId_key"
  ON "FeishuUserIdentity"("connectionId", "userId");
CREATE INDEX "FeishuUserIdentity_userId_idx"
  ON "FeishuUserIdentity"("userId");

ALTER TABLE "FeishuUserIdentity"
  ADD CONSTRAINT "FeishuUserIdentity_connectionId_fkey"
  FOREIGN KEY ("connectionId") REFERENCES "OrganizationFeishuApplicationConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "FeishuUserIdentity"
  ADD CONSTRAINT "FeishuUserIdentity_userId_fkey"
  FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
