CREATE TABLE IF NOT EXISTS fabric_service_channel_route_rebuild_attempts (
    id UUID PRIMARY KEY,
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    reporter_node_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    service_class TEXT NOT NULL,
    route_id TEXT NOT NULL,
    replacement_route_id TEXT NOT NULL DEFAULT '',
    rebuild_request_id TEXT NOT NULL,
    rebuild_status TEXT NOT NULL,
    rebuild_reason TEXT NOT NULL DEFAULT '',
    rebuild_attempt INTEGER NOT NULL DEFAULT 0,
    decision_source TEXT NOT NULL,
    outcome TEXT NOT NULL,
    generation TEXT NOT NULL DEFAULT '',
    policy_fingerprint TEXT NOT NULL DEFAULT '',
    observed_policy_fingerprint TEXT NOT NULL DEFAULT '',
    observed_route_generation TEXT NOT NULL DEFAULT '',
    effective_route_generation TEXT NOT NULL DEFAULT '',
    feedback_status TEXT NOT NULL DEFAULT '',
    feedback_score_adjustment INTEGER NOT NULL DEFAULT 0,
    feedback_effective_score_adjustment INTEGER NOT NULL DEFAULT 0,
    feedback_reasons TEXT[] NOT NULL DEFAULT '{}',
    last_error TEXT NOT NULL DEFAULT '',
    consecutive_failures INTEGER NOT NULL DEFAULT 0,
    stall_count INTEGER NOT NULL DEFAULT 0,
    last_send_duration_ms BIGINT NOT NULL DEFAULT 0,
    quality_window_sample_count INTEGER NOT NULL DEFAULT 0,
    quality_window_failure_count INTEGER NOT NULL DEFAULT 0,
    quality_window_drop_count INTEGER NOT NULL DEFAULT 0,
    quality_window_slow_count INTEGER NOT NULL DEFAULT 0,
    old_hops TEXT[] NOT NULL DEFAULT '{}',
    replacement_hops TEXT[] NOT NULL DEFAULT '{}',
    payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (cluster_id, reporter_node_id, service_class, route_id, rebuild_request_id)
);

CREATE INDEX IF NOT EXISTS idx_fsc_rebuild_attempts_cluster_reporter_updated
    ON fabric_service_channel_route_rebuild_attempts (cluster_id, reporter_node_id, updated_at DESC);

CREATE INDEX IF NOT EXISTS idx_fsc_rebuild_attempts_cluster_route_updated
    ON fabric_service_channel_route_rebuild_attempts (cluster_id, route_id, updated_at DESC);
