-- 创建公共 Outbox；该表及全部公共索引、约束只由 tech-public-foundation 维护。
CREATE TABLE tb_outbox_event (
    id bigserial PRIMARY KEY,
    event_id varchar(64) NOT NULL,
    event_type varchar(150) NOT NULL,
    payload_version integer NOT NULL DEFAULT 1,
    aggregate_type varchar(100) NOT NULL,
    aggregate_id varchar(100) NOT NULL,
    resource_type varchar(100) NOT NULL,
    resource_id varchar(100) NOT NULL,
    business_key varchar(150) NOT NULL DEFAULT '',
    request_id varchar(100) NOT NULL DEFAULT '',
    correlation_id varchar(100) NOT NULL DEFAULT '',
    payload jsonb NOT NULL,
    status integer NOT NULL DEFAULT 1,
    retry_count integer NOT NULL DEFAULT 0,
    max_retries integer NOT NULL DEFAULT 10,
    next_attempt_at timestamptz NOT NULL DEFAULT NOW(),
    lease_owner varchar(100),
    lease_expires_at timestamptz,
    last_error_code varchar(100) NOT NULL DEFAULT '',
    last_error_summary varchar(500) NOT NULL DEFAULT '',
    delivered_at timestamptz,
    created_at timestamptz NOT NULL DEFAULT NOW(),
    updated_at timestamptz NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_outbox_event_id UNIQUE (event_id),
    CONSTRAINT ck_outbox_event_status CHECK (status IN (1, 2, 3, 4)),
    CONSTRAINT ck_outbox_event_payload_version CHECK (payload_version > 0),
    CONSTRAINT ck_outbox_event_retry_count CHECK (retry_count >= 0 AND max_retries > 0)
);

CREATE INDEX idx_outbox_event_claim
    ON tb_outbox_event (status, next_attempt_at, lease_expires_at, created_at);
CREATE INDEX idx_outbox_event_type_status
    ON tb_outbox_event (event_type, status);
CREATE INDEX idx_outbox_event_aggregate
    ON tb_outbox_event (aggregate_type, aggregate_id, created_at);
CREATE INDEX idx_outbox_event_resource
    ON tb_outbox_event (resource_type, resource_id, created_at);
CREATE INDEX idx_outbox_event_request_id ON tb_outbox_event (request_id) WHERE request_id <> '';
CREATE INDEX idx_outbox_event_correlation_id ON tb_outbox_event (correlation_id) WHERE correlation_id <> '';

COMMENT ON TABLE tb_outbox_event IS '公共可靠事件 Outbox';
COMMENT ON COLUMN tb_outbox_event.status IS '投递状态 1=待投递, 2=投递中, 3=已投递, 4=投递失败';
