-- 创建企业微信自建应用安全配置表；凭据仅保存 AES-256-GCM 密文。
CREATE TABLE IF NOT EXISTS tb_wecom_application (
    id bigserial PRIMARY KEY,
    corp_id varchar(64) NOT NULL,
    agent_id bigint NOT NULL,
    name varchar(100) NOT NULL,
    secret_ciphertext bytea NOT NULL,
    callback_token_ciphertext bytea NOT NULL,
    encoding_aes_key_ciphertext bytea NOT NULL,
    status integer NOT NULL DEFAULT 1,
    created_by bigint NOT NULL,
    updated_by bigint NOT NULL,
    last_connected_at timestamptz,
    created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at timestamptz,
    CONSTRAINT chk_wecom_application_status CHECK (status IN (0, 1)),
    CONSTRAINT chk_wecom_application_agent_id CHECK (agent_id > 0)
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_wecom_application_identity
    ON tb_wecom_application (corp_id, agent_id)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_wecom_application_status
    ON tb_wecom_application (status, id)
    WHERE deleted_at IS NULL;

COMMENT ON TABLE tb_wecom_application IS '企业微信自建应用安全连接配置';
COMMENT ON COLUMN tb_wecom_application.secret_ciphertext IS '应用 Secret 的 AES-256-GCM 密文';
COMMENT ON COLUMN tb_wecom_application.callback_token_ciphertext IS '回调 Token 的 AES-256-GCM 密文';
COMMENT ON COLUMN tb_wecom_application.encoding_aes_key_ciphertext IS '回调 EncodingAESKey 的 AES-256-GCM 密文';
