-- Creator/Affiliate authorization is intentionally separate from seller
-- TikTokConnection rows. Creator tokens must not be used for seller APIs.
CREATE TABLE "tiktok_creator_connections" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "encryptedAccessToken" TEXT NOT NULL,
    "encryptedRefreshToken" TEXT,
    "tokenExpiresAt" TIMESTAMP(3),
    "refreshTokenExpiresAt" TIMESTAMP(3),
    "scope" TEXT,
    "grantedScopes" TEXT,
    "userType" INTEGER NOT NULL DEFAULT 1,
    "openId" TEXT,
    "creatorName" TEXT,
    "region" TEXT,
    "status" "TikTokConnectionStatus" NOT NULL DEFAULT 'CONNECTED',
    "lastRefreshAt" TIMESTAMP(3),
    "connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "tiktok_creator_connections_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "tiktok_creator_connections_userId_key" ON "tiktok_creator_connections"("userId");
CREATE INDEX "tiktok_creator_connections_userId_idx" ON "tiktok_creator_connections"("userId");
CREATE INDEX "tiktok_creator_connections_status_idx" ON "tiktok_creator_connections"("status");

ALTER TABLE "tiktok_creator_connections"
  ADD CONSTRAINT "tiktok_creator_connections_userId_fkey"
  FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
