-- CreateTable: referral_query_view
-- 推荐关系查询视图 - 通过 Debezium CDC 从 referral-service 同步
CREATE TABLE "referral_query_view" (
    "relationship_id" BIGINT NOT NULL,
    "user_id" BIGINT NOT NULL,
    "account_sequence" VARCHAR(12) NOT NULL,
    "referrer_id" BIGINT,
    "root_user_id" BIGINT,
    "my_referral_code" VARCHAR(20) NOT NULL,
    "used_referral_code" VARCHAR(20),
    "ancestor_path" BIGINT[] NOT NULL DEFAULT '{}',
    "depth" INTEGER NOT NULL DEFAULT 0,
    "direct_referral_count" INTEGER NOT NULL DEFAULT 0,
    "active_direct_count" INTEGER NOT NULL DEFAULT 0,
    "created_at" TIMESTAMP(3) NOT NULL,
    "synced_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "referral_query_view_pkey" PRIMARY KEY ("relationship_id")
);

-- CreateIndex: unique constraints
CREATE UNIQUE INDEX "referral_query_view_user_id_key" ON "referral_query_view"("user_id");
CREATE UNIQUE INDEX "referral_query_view_account_sequence_key" ON "referral_query_view"("account_sequence");
CREATE UNIQUE INDEX "referral_query_view_my_referral_code_key" ON "referral_query_view"("my_referral_code");

-- CreateIndex: query indexes
CREATE INDEX "referral_query_view_referrer_id_idx" ON "referral_query_view"("referrer_id");
CREATE INDEX "referral_query_view_account_sequence_idx" ON "referral_query_view"("account_sequence");
CREATE INDEX "referral_query_view_my_referral_code_idx" ON "referral_query_view"("my_referral_code");
CREATE INDEX "referral_query_view_used_referral_code_idx" ON "referral_query_view"("used_referral_code");
CREATE INDEX "referral_query_view_root_user_id_idx" ON "referral_query_view"("root_user_id");
CREATE INDEX "referral_query_view_depth_idx" ON "referral_query_view"("depth");
