-- Durable access evidence written atomically by the gateway realtime snapshot writer.
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_first_seen_at DATETIME(3) NULL AFTER event_id;
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_previous_received_at DATETIME(3) NULL AFTER access_first_seen_at;
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_latest_received_at DATETIME(3) NULL AFTER access_previous_received_at;
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_report_interval_ms BIGINT UNSIGNED NULL AFTER access_latest_received_at;
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_sample_count BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER access_report_interval_ms;
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_latest_event_id VARCHAR(64) NOT NULL DEFAULT '' AFTER access_sample_count;
ALTER TABLE vehicle_realtime_snapshot ADD COLUMN access_first_seen_source VARCHAR(32) NOT NULL DEFAULT '' AFTER access_latest_event_id;

UPDATE vehicle_realtime_snapshot
SET access_first_seen_at = COALESCE(access_first_seen_at, received_at, updated_at),
    access_latest_received_at = COALESCE(access_latest_received_at, received_at, updated_at),
    access_sample_count = IF(access_sample_count = 0, 1, access_sample_count),
    access_latest_event_id = IF(access_latest_event_id = '', event_id, access_latest_event_id),
    access_first_seen_source = IF(access_first_seen_source = '', 'snapshot_backfill', access_first_seen_source)
WHERE access_first_seen_at IS NULL
   OR access_latest_received_at IS NULL
   OR access_sample_count = 0
   OR access_latest_event_id = ''
   OR access_first_seen_source = '';

CREATE INDEX idx_access_latest ON vehicle_realtime_snapshot(access_latest_received_at, vin);
