-- 创建外部集成尝试权威记录；不建立外键，业务关系通过稳定 ID 显式维护。
CREATE TABLE tb_integration_log (
    id bigserial PRIMARY KEY,
    integration_id varchar(64) NOT NULL,
    idempotency_key varchar(160),
    provider varchar(32) NOT NULL,
    direction varchar(16) NOT NULL,
    operation varchar(64) NOT NULL,
    external_id varchar(128),
    resource_type varchar(64),
    resource_id varchar(128),
    resource_key varchar(128),
    trigger_source varchar(32),
    trigger_scene varchar(128),
    trigger_series varchar(64),
    scheduled_at timestamptz,
    started_at timestamptz,
    attempt integer NOT NULL DEFAULT 1,
    result varchar(20) NOT NULL,
    http_status integer,
    provider_code varchar(64),
    provider_message varchar(500),
    request_summary jsonb,
    response_summary jsonb,
    content_hash varchar(64) NOT NULL DEFAULT '',
    duration_ms bigint NOT NULL DEFAULT 0,
    state_changed boolean NOT NULL DEFAULT false,
    metadata jsonb,
    recovery_strategy varchar(255),
    request_id varchar(64),
    correlation_id varchar(64),
    audit_event_id bigint,
    created_at timestamptz NOT NULL DEFAULT NOW(),
    updated_at timestamptz NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_integration_log_id UNIQUE (integration_id),
    CONSTRAINT uq_integration_log_idempotency UNIQUE (provider, operation, idempotency_key),
    CONSTRAINT ck_integration_log_direction CHECK (direction IN ('inbound', 'outbound')),
    CONSTRAINT ck_integration_log_result CHECK (result IN (
        'pending', 'success', 'failed', 'unknown', 'not_found', 'invalid_payload',
        'ignored', 'merged', 'rate_limited', 'completed', 'cancelled'
    )),
    CONSTRAINT ck_integration_log_attempt CHECK (attempt > 0),
    CONSTRAINT ck_integration_log_duration CHECK (duration_ms >= 0)
);

CREATE INDEX idx_integration_log_time ON tb_integration_log (created_at DESC, id DESC);
CREATE INDEX idx_integration_log_provider ON tb_integration_log (provider, operation, result, created_at DESC);
CREATE INDEX idx_integration_log_resource ON tb_integration_log (resource_type, resource_id, created_at DESC);
CREATE INDEX idx_integration_log_resource_key ON tb_integration_log (resource_type, resource_key, created_at DESC);
CREATE INDEX idx_integration_log_trigger ON tb_integration_log (trigger_series, attempt);
CREATE INDEX idx_integration_log_request ON tb_integration_log (request_id, created_at ASC) WHERE request_id IS NOT NULL;
CREATE INDEX idx_integration_log_correlation ON tb_integration_log (correlation_id, created_at ASC) WHERE correlation_id IS NOT NULL;

COMMENT ON TABLE tb_integration_log IS '外部集成调用、回调及未发送尝试记录';
COMMENT ON COLUMN tb_integration_log.result IS '尝试结果，pending 仅为内部执行态，其余为公开终态';
