CREATE TABLE IF NOT EXISTS failure_events (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    source VARCHAR(64) NOT NULL,
    external_id VARCHAR(255) NOT NULL,
    component_id BIGINT NOT NULL,
    asset_id BIGINT NULL,
    failure_type VARCHAR(128) NOT NULL,
    failure_time TIMESTAMP NOT NULL,
    details TEXT NULL,
    confidence DECIMAL(5,2) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_failure_events_component
        FOREIGN KEY (component_id) REFERENCES components(id)
        ON DELETE RESTRICT ON UPDATE CASCADE,
    CONSTRAINT fk_failure_events_asset
        FOREIGN KEY (asset_id) REFERENCES assets(id)
        ON DELETE SET NULL ON UPDATE CASCADE,
    UNIQUE KEY uniq_failure_events_source_external (source, external_id)
);

CREATE INDEX idx_failure_events_component_time ON failure_events(component_id, failure_time, id);
CREATE INDEX idx_failure_events_asset_time ON failure_events(asset_id, failure_time, id);
CREATE INDEX idx_failure_events_time ON failure_events(failure_time, id);
