-- 增加系统账号企微身份绑定，并保存应用可见成员选择快照。
ALTER TABLE tb_account
    ADD COLUMN IF NOT EXISTS wecom_corp_id varchar(64) NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS wecom_userid varchar(64) NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS wecom_name varchar(100) NOT NULL DEFAULT '';

CREATE UNIQUE INDEX IF NOT EXISTS uq_account_wecom_identity
    ON tb_account (wecom_corp_id, wecom_userid)
    WHERE deleted_at IS NULL AND wecom_corp_id <> '' AND wecom_userid <> '';

CREATE TABLE IF NOT EXISTS tb_wecom_member (
    id bigserial PRIMARY KEY,
    application_id bigint NOT NULL,
    corp_id varchar(64) NOT NULL,
    userid varchar(64) NOT NULL,
    name varchar(100) NOT NULL,
    department_ids jsonb NOT NULL DEFAULT '[]'::jsonb,
    visible boolean NOT NULL DEFAULT true,
    synced_at timestamptz NOT NULL,
    created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT chk_wecom_member_application_id CHECK (application_id > 0),
    CONSTRAINT chk_wecom_member_userid CHECK (length(btrim(userid)) > 0)
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_wecom_member_identity
    ON tb_wecom_member (application_id, userid);

CREATE INDEX IF NOT EXISTS idx_wecom_member_visible_name
    ON tb_wecom_member (application_id, visible, name, userid);

COMMENT ON TABLE tb_wecom_member IS '企业微信应用可见成员的本地选择快照，不作为组织模型';
COMMENT ON COLUMN tb_wecom_member.department_ids IS '企微部门 ID 列表，仅用于管理员辨认成员';
COMMENT ON COLUMN tb_account.wecom_corp_id IS '绑定的企业微信企业 ID';
COMMENT ON COLUMN tb_account.wecom_userid IS '绑定的企业微信成员 userid，入库前统一转为小写';
COMMENT ON COLUMN tb_account.wecom_name IS '绑定时的企业微信成员姓名快照';
