ALTER TABLE components
    ADD COLUMN first_seen_at TIMESTAMP NULL;

CREATE TABLE IF NOT EXISTS log_bundles (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    asset_id BIGINT NOT NULL,
    collected_at TIMESTAMP NOT NULL,
    content_hash CHAR(64) NOT NULL,
    payload JSON NOT NULL,
    source VARCHAR(255) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_log_bundles_asset
        FOREIGN KEY (asset_id) REFERENCES assets(id)
        ON DELETE RESTRICT ON UPDATE CASCADE,
    UNIQUE KEY uniq_log_bundles_content_hash (content_hash)
);

CREATE TABLE IF NOT EXISTS observations (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    log_bundle_id BIGINT NOT NULL,
    asset_id BIGINT NOT NULL,
    component_id BIGINT NOT NULL,
    observed_at TIMESTAMP NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_observations_log_bundle
        FOREIGN KEY (log_bundle_id) REFERENCES log_bundles(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT fk_observations_asset
        FOREIGN KEY (asset_id) REFERENCES assets(id)
        ON DELETE RESTRICT ON UPDATE CASCADE,
    CONSTRAINT fk_observations_component
        FOREIGN KEY (component_id) REFERENCES components(id)
        ON DELETE RESTRICT ON UPDATE CASCADE,
    UNIQUE KEY uniq_observations_bundle_component (log_bundle_id, component_id)
);

CREATE INDEX idx_observations_component ON observations(component_id);
CREATE INDEX idx_observations_asset ON observations(asset_id);
CREATE INDEX idx_observations_log_bundle ON observations(log_bundle_id);
