CREATE TABLE IF NOT EXISTS vehicle_open_mileage_snapshot (
    snapshot_id CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
    app_id BIGINT UNSIGNED NOT NULL,
    request_hash BINARY(32) NOT NULL,
    start_date DATE NOT NULL,
    end_date DATE NOT NULL,
    vehicle_count INT UNSIGNED NOT NULL,
    created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    expires_at DATETIME(3) NOT NULL,
    INDEX idx_open_mileage_snapshot_expiry (expires_at),
    INDEX idx_open_mileage_snapshot_app (app_id, created_at),
    CONSTRAINT fk_open_mileage_snapshot_app
        FOREIGN KEY (app_id) REFERENCES vehicle_open_app(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS vehicle_open_mileage_snapshot_vehicle (
    snapshot_id CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
    ordinal INT UNSIGNED NOT NULL,
    vin VARCHAR(64) NOT NULL,
    plate VARCHAR(64) NOT NULL,
    PRIMARY KEY (snapshot_id, ordinal),
    UNIQUE KEY uk_open_mileage_snapshot_plate (snapshot_id, plate),
    INDEX idx_open_mileage_snapshot_vin (snapshot_id, vin),
    CONSTRAINT fk_open_mileage_snapshot_vehicle
        FOREIGN KEY (snapshot_id) REFERENCES vehicle_open_mileage_snapshot(snapshot_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE INDEX idx_daily_mileage_source_open_selected
    ON vehicle_daily_mileage_source(vin, stat_date, protocol, is_selected, latest_event_time);
