-- 新增个人客户 OpenID 关联表
-- 保存客户在不同微信应用（公众号/小程序）下的 OpenID 记录
CREATE TABLE IF NOT EXISTS tb_personal_customer_openid (
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ,
    customer_id BIGINT NOT NULL,
    app_id VARCHAR(100) NOT NULL,
    open_id VARCHAR(100) NOT NULL,
    union_id VARCHAR(100) NOT NULL DEFAULT '',
    app_type VARCHAR(20) NOT NULL DEFAULT ''
);

-- 软删除条件下的唯一索引：同一应用下 OpenID 唯一
CREATE UNIQUE INDEX IF NOT EXISTS idx_pco_app_id_open_id
    ON tb_personal_customer_openid (app_id, open_id)
    WHERE deleted_at IS NULL;

-- 客户ID索引：按客户查询所有 OpenID 记录
CREATE INDEX IF NOT EXISTS idx_pco_customer_id
    ON tb_personal_customer_openid (customer_id);

-- UnionID索引：按 UnionID 回查合并客户
CREATE INDEX IF NOT EXISTS idx_pco_union_id
    ON tb_personal_customer_openid (union_id)
    WHERE union_id != '' AND deleted_at IS NULL;

-- 字段注释
COMMENT ON TABLE tb_personal_customer_openid IS '个人客户OpenID关联表';
COMMENT ON COLUMN tb_personal_customer_openid.customer_id IS '关联个人客户ID';
COMMENT ON COLUMN tb_personal_customer_openid.app_id IS '微信应用标识（公众号或小程序AppID）';
COMMENT ON COLUMN tb_personal_customer_openid.open_id IS '当前应用下的OpenID';
COMMENT ON COLUMN tb_personal_customer_openid.union_id IS '微信开放平台统一标识（可选）';
COMMENT ON COLUMN tb_personal_customer_openid.app_type IS '应用类型（official_account/miniapp）';
