1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! Vertiport-related utilities

use super::flight_plan::*;
use super::schedule::*;
use super::vehicle::*;
use super::{best_path, BestPathError, BestPathRequest};
use crate::grpc::client::GrpcClients;
use chrono::Duration;
use std::cmp::{max, min};
use std::collections::HashMap;
use std::str::FromStr;
use svc_gis_client_grpc::prelude::gis::*;
use svc_storage_client_grpc::prelude::*;

/// Chop up larger timeslots into smaller durations to avoid temporary no-fly zones
const MAX_DURATION_TIMESLOT_MINUTES: i64 = 30;

/// Error type for vertiport-related errors
#[derive(Debug, Copy, Clone)]
pub enum VertiportError {
    /// Error communicating with a client
    ClientError,

    /// Invalid data
    InvalidData,

    /// No vertipads found
    NoVertipads,

    /// No schedule found
    NoSchedule,

    /// Invalid schedule
    InvalidSchedule,

    /// Internal error
    Internal,
}

impl std::fmt::Display for VertiportError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            VertiportError::ClientError => write!(f, "Client error"),
            VertiportError::InvalidData => write!(f, "Invalid data"),
            VertiportError::NoVertipads => write!(f, "No vertipads"),
            VertiportError::NoSchedule => write!(f, "No schedule"),
            VertiportError::InvalidSchedule => write!(f, "Invalid schedule"),
            VertiportError::Internal => write!(f, "Internal error"),
        }
    }
}

pub enum GetVertipadsArg {
    VertiportId(String),
    VertipadIds(Vec<String>),
}

/// Gets all vertipads for a vertiport
pub async fn get_vertipads(
    clients: &GrpcClients,
    arg: GetVertipadsArg,
) -> Result<Vec<String>, VertiportError> {
    let mut filter = AdvancedSearchFilter::search_is_null("deleted_at".to_owned())
        .and_equals("enabled".to_string(), "1".to_string());

    match arg {
        GetVertipadsArg::VertiportId(vertiport_id) => {
            filter = filter.and_equals("vertiport_id".to_string(), vertiport_id);
        }
        GetVertipadsArg::VertipadIds(ids) => {
            filter = filter.and_in("vertipad_id".to_string(), ids);
        }
    }

    router_info!("(get_vertipads) proposed filter: {:?}", filter.clone());

    let filter = AdvancedSearchFilter::default();
    let Ok(response) = clients.storage.vertipad.search(filter).await else {
        router_error!("(get_vertipads) Failed to get vertipads.");
        return Err(VertiportError::NoVertipads);
    };

    router_info!("(get_vertipads) response: {:?}", response);

    Ok(response
        .into_inner()
        .list
        .into_iter()
        // in R3 the search filter is not working, do an extra filter here
        .filter_map(|vp| {
            let Some(data) = vp.data else {
                return None;
            };

            if !data.enabled {
                return None;
            }

            Some(vp.id)
        })
        .collect::<Vec<String>>())
}

/// Get pairs of timeslots where a flight can leave within the origin timeslot
///  and land within the target timeslot
#[allow(clippy::too_many_arguments)]
pub async fn get_timeslot_pairs(
    origin_vertiport_id: &str,
    origin_vertipad_id: Option<&str>,
    target_vertiport_id: &str,
    target_vertipad_id: Option<&str>,
    origin_time_block: &Duration,
    target_time_block: &Duration,
    timeslot: &Timeslot,
    existing_flight_plans: &[FlightPlanSchedule],
    clients: &GrpcClients,
) -> Result<Vec<TimeslotPair>, VertiportError> {
    let origin_timeslots = get_available_timeslots(
        origin_vertiport_id,
        origin_vertipad_id,
        existing_flight_plans,
        timeslot,
        origin_time_block,
        clients,
    )
    .await?;

    let target_timeslots = get_available_timeslots(
        target_vertiport_id,
        target_vertipad_id,
        existing_flight_plans,
        timeslot,
        target_time_block,
        clients,
    )
    .await?;

    get_vertipad_timeslot_pairs(
        origin_vertiport_id,
        target_vertiport_id,
        origin_timeslots,
        target_timeslots,
        clients,
    )
    .await
}

/// Return a map of vertipad ids to available timeslots for that vertipad
///
/// TODO(R4): This will be replaced with a call to svc-storage vertipad_timeslots to
///  return a list of available timeslots for each vertipad, so we don't
///  need to rebuild each pad's schedule from flight plans each time
async fn get_available_timeslots(
    vertiport_id: &str,
    vertipad_id: Option<&str>,
    existing_flight_plans: &[FlightPlanSchedule],
    timeslot: &Timeslot,
    minimum_duration: &Duration,
    clients: &GrpcClients,
) -> Result<HashMap<String, Vec<Timeslot>>, VertiportError> {
    // Get vertiport schedule
    let calendar = get_vertiport_calendar(vertiport_id, clients).await?;

    // TODO(R4): Use each vertipad's calendar
    let base_timeslots = calendar
        .to_timeslots(&timeslot.time_start, &timeslot.time_end)
        .map_err(|e| {
            router_error!("(get_available_timeslots) Could not convert calendar to timeslots: {e}");
            VertiportError::Internal
        })?;

    router_debug!(
        "(get_available_timeslots) base_timeslots: {:?}",
        base_timeslots
    );

    // TODO(R4): This is currently hardcoded, get the duration of the timeslot
    // try min and max both the necessary landing time
    let max_duration = Duration::try_minutes(MAX_DURATION_TIMESLOT_MINUTES).ok_or_else(|| {
        router_error!("(get_available_timeslots) error creating time delta.");
        VertiportError::Internal
    })?;

    let filter = match vertipad_id {
        Some(id) => GetVertipadsArg::VertipadIds(vec![id.to_string()]),
        None => GetVertipadsArg::VertiportId(vertiport_id.to_string()),
    };

    // Prepare a list of slots for each vertipad
    // For now, each vertipad shares the same schedule as the vertiport itself
    let mut timeslots = get_vertipads(clients, filter)
        .await?
        .into_iter()
        .map(|id| (id, base_timeslots.clone()))
        .collect::<HashMap<String, Vec<Timeslot>>>();

    // Get occupied slots
    // TODO(R4): This will be replaced with a call to svc-storage vertipad_timeslots to
    //  return a list of occupied timeslots for each vertipad, so we don't
    //  need to rebuild each pad's schedule from flight plans each time
    let occupied_slots = build_timeslots_from_flight_plans(vertiport_id, existing_flight_plans)?;

    router_debug!("(get_available_timeslots): vertiport: {:?}", vertiport_id);
    router_debug!("(get_available_timeslots): vertipads {:?}", timeslots);
    router_debug!(
        "(get_available_timeslots): occupied {:?}",
        occupied_slots
            .iter()
            .map(|(id, _)| id)
            .collect::<Vec<&String>>()
    );

    // For each occupied slot, remove it from the list of available slots
    for (vertipad_id, occupied_slot) in occupied_slots.iter() {
        let Some(vertipad_slots) = timeslots.get_mut(vertipad_id) else {
            router_error!("(get_available_timeslots) Vertipad {} (from a flight plan) not found in list of vertipads from storage.", vertipad_id);
            continue;
        };

        *vertipad_slots = vertipad_slots
            .iter_mut()
            // Subtract the occupation slot from the available slots
            .flat_map(|slot| *slot - *occupied_slot)
            // Split any slots that are too long. A short temporary no-fly zone overlapping
            //  any part of the timeslot will invalidate the entire timeslot, so we split it
            //  into smaller timeslots to avoid this.
            .flat_map(|slot| slot.split(minimum_duration, &max_duration))
            .collect::<Vec<Timeslot>>();
    }

    Ok(timeslots)
}

/// Gets vertiport schedule from storage and converts it to a Calendar object.
async fn get_vertiport_calendar(
    vertiport_id: &str,
    clients: &GrpcClients,
) -> Result<Calendar, VertiportError> {
    let vertiport_object = match clients
        .storage
        .vertiport
        .get_by_id(Id {
            id: vertiport_id.to_string(),
        })
        .await
    {
        Ok(response) => response.into_inner(),
        Err(e) => {
            let error_str = format!("Could not retrieve data for vertiport {vertiport_id}.");

            router_error!("(get_vertiport_calendar) {}: {e}", error_str);
            return Err(VertiportError::ClientError);
        }
    };

    let vertiport_data = match vertiport_object.data {
        Some(d) => d,
        None => {
            let error_str = format!("Date invalid for vertiport {}.", vertiport_id);
            router_error!("(get_vertiport_calendar) {}", error_str);
            return Err(VertiportError::InvalidData);
        }
    };

    let Some(vertiport_schedule) = vertiport_data.schedule else {
        let error_str = format!("No schedule for vertiport {}.", vertiport_id);
        router_error!("(get_vertiport_calendar) {}", error_str);
        return Err(VertiportError::NoSchedule);
    };

    match Calendar::from_str(&vertiport_schedule) {
        Ok(calendar) => Ok(calendar),
        Err(e) => {
            let error_str = format!("Schedule invalid for vertiport {}.", vertiport_id);
            router_error!("(get_vertiport_calendar) {}: {}", error_str, e);
            Err(VertiportError::InvalidSchedule)
        }
    }
}

/// Gets all occupied vertipad time slots given flight plans.
///  If `invert` is true, returns all unoccupied time slots.
///
/// TODO(R4): Remove in favor of read from storage vertipad_timeslot table
///  where the duration of the timeslot is stored
fn build_timeslots_from_flight_plans(
    vertiport_id: &str,
    flight_plans: &[FlightPlanSchedule],
) -> Result<Vec<(String, Timeslot)>, VertiportError> {
    // TODO(R4): This is currently hardcoded, get the duration of the timeslot
    //  directly from the vertipad_timeslot object
    let required_loading_time =
        Duration::try_seconds(crate::grpc::api::query_flight::LOADING_AND_TAKEOFF_TIME_SECONDS)
            .ok_or_else(|| {
                router_error!("(build_timeslots_from_flight_plans) error creating time delta.");
                VertiportError::Internal
            })?;

    let required_unloading_time =
        Duration::try_seconds(crate::grpc::api::query_flight::LANDING_AND_UNLOADING_TIME_SECONDS)
            .ok_or_else(|| {
            router_error!("(build_timeslots_from_flight_plans) error creating time delta.");
            VertiportError::Internal
        })?;

    let results = flight_plans
        .iter()
        .filter_map(|fp| {
            if *vertiport_id == fp.origin_vertiport_id {
                let timeslot = Timeslot {
                    time_start: fp.origin_timeslot_start,
                    // TODO(R4): duration should be retrieved from flight plan object
                    //  instead of being hardcoded
                    time_end: fp.origin_timeslot_start + required_loading_time,
                };

                Some((fp.origin_vertipad_id.clone(), timeslot))
            } else if *vertiport_id == fp.target_vertiport_id {
                let timeslot = Timeslot {
                    time_start: fp.target_timeslot_start,
                    // TODO(R4): duration should be retrieved from flight plan object
                    //  instead of being hardcoded
                    time_end: fp.target_timeslot_start + required_unloading_time,
                };

                Some((fp.target_vertipad_id.clone(), timeslot))
            } else {
                None
            }
        })
        .collect::<Vec<(String, Timeslot)>>();

    Ok(results)
}

/// Gets all available timeslot pairs and a path for each pair
#[derive(Debug, Clone)]
pub struct TimeslotPair {
    pub origin_vertiport_id: String,
    pub origin_vertipad_id: String,
    pub origin_timeslot: Timeslot,
    pub target_vertiport_id: String,
    pub target_vertipad_id: String,
    pub target_timeslot: Timeslot,
    pub path: Vec<PointZ>,
    pub distance_meters: f32,
}

impl From<TimeslotPair> for flight_plan::Data {
    fn from(val: TimeslotPair) -> Self {
        let points = val
            .path
            .iter()
            .map(|p| GeoPoint {
                latitude: p.latitude,
                longitude: p.longitude,
                // TODO(R5): put altitude information in storage
            })
            .collect();

        let path = Some(GeoLineString { points });
        flight_plan::Data {
            origin_vertiport_id: Some(val.origin_vertiport_id),
            origin_vertipad_id: val.origin_vertipad_id,
            origin_timeslot_start: Some(val.origin_timeslot.time_start.into()),
            origin_timeslot_end: Some(val.origin_timeslot.time_end.into()),
            target_vertiport_id: Some(val.target_vertiport_id),
            target_vertipad_id: val.target_vertipad_id,
            target_timeslot_start: Some(val.target_timeslot.time_start.into()),
            target_timeslot_end: Some(val.target_timeslot.time_end.into()),
            path,
            ..Default::default()
        }
    }
}

/// Attempts to find a pairing of origin and target pad
///  timeslots wherein a flight could occur.
pub async fn get_vertipad_timeslot_pairs(
    origin_vertiport_id: &str,
    target_vertiport_id: &str,
    mut origin_vertipads: HashMap<String, Vec<Timeslot>>,
    mut target_vertipads: HashMap<String, Vec<Timeslot>>,
    clients: &GrpcClients,
) -> Result<Vec<TimeslotPair>, VertiportError> {
    let mut pairs = vec![];

    let mut best_path_request = BestPathRequest {
        origin_identifier: origin_vertiport_id.to_string(),
        target_identifier: target_vertiport_id.to_string(),
        origin_type: NodeType::Vertiport as i32,
        target_type: NodeType::Vertiport as i32,
        time_start: None,
        time_end: None,
        limit: 5,
    };

    // Iterate through origin pads and their schedules
    for (origin_vertipad_id, origin_schedule) in origin_vertipads.iter_mut() {
        origin_schedule.sort_by(|a, b| a.time_end.cmp(&b.time_end));

        // Iterate through the available timeslots for this pad
        'origin_timeslots: for dts in origin_schedule.iter() {
            // Iterate through target pads and their schedules
            for (target_vertipad_id, target_schedule) in target_vertipads.iter_mut() {
                target_schedule.sort_by(|a, b| a.time_start.cmp(&b.time_start));

                // Iterate through available timeslots for this pad
                // There will be several opportunities to break out without
                //  excess work
                for ats in target_schedule.iter() {
                    // no timeslot overlap possible
                    //                    | origin timeslot |
                    // | target timeslot |
                    if dts.time_start >= ats.time_end {
                        continue;
                    }

                    // Temporary no-fly zones make checking the same route
                    //  multiple times necessary for different timeslots
                    best_path_request.time_start = Some(dts.time_start.into());
                    best_path_request.time_end = Some(ats.time_end.into());

                    let paths = match best_path(&best_path_request, clients).await {
                        Ok(paths) => paths,
                        Err(BestPathError::NoPathFound) => {
                            // no path found, perhaps temporary no-fly zone
                            //  is blocking journeys from this depart timeslot
                            // Break out and try the next depart timeslot
                            router_debug!(
                                "(get_vertipad_timeslot_pairs) No path found from vertiport {}
                                to vertiport {} (from {} to {}).",
                                origin_vertiport_id,
                                target_vertiport_id,
                                dts.time_start,
                                ats.time_end
                            );

                            break 'origin_timeslots;
                        }
                        Err(BestPathError::ClientError) => {
                            // exit immediately if svc-gis is down, don't allow new flights
                            router_error!(
                                "(get_vertipad_timeslot_pairs) Could not determine path."
                            );
                            return Err(VertiportError::ClientError);
                        }
                    };

                    // For now only get the first path
                    let Some(path) = paths.first() else {
                        // no path found, perhaps temporary no-fly zone
                        //  is blocking journeys from this depart timeslot
                        // Break out and try the next depart timeslot
                        router_debug!(
                            "(get_vertipad_timeslot_pairs) No path found from vertiport {}
                            to vertiport {} (from {} to {}).",
                            origin_vertiport_id,
                            target_vertiport_id,
                            dts.time_start,
                            ats.time_end
                        );

                        break 'origin_timeslots;
                    };

                    let distance_meters = path.1 as f32;
                    let path = path.0.clone();
                    let estimated_duration_s = estimate_flight_time_seconds(&distance_meters)
                        .map_err(|e| {
                            router_error!(
                                "(get_vertipad_timeslot_pairs) Could not estimate flight time: {e}"
                            );
                            VertiportError::Internal
                        })?;

                    // Since both schedules are sorted, we can break early once
                    //  origin end time + flight time is less than the target timeslot's start time
                    //  and not look at the other timeslots for that pad
                    // | origin timeslot |
                    //                      ---->x
                    //                                | target timeslot 1 | target timeslot 2 |
                    // (the next target timeslot start to be checked would be even further away)
                    if dts.time_end + estimated_duration_s < ats.time_start {
                        break;
                    }

                    //
                    // |     dts              |          (depart timeslot)
                    //       ----->        ----->        (flight time)
                    //            |      ats     |       (target timeslot)
                    //       | actual dts  |             (actual depart timeslot)
                    //
                    // The actual origin_timeslot is the timeslot within which origin
                    //  will result in landing in the target timeslot.
                    let origin_timeslot = Timeslot {
                        time_start: max(dts.time_start, ats.time_start - estimated_duration_s),
                        time_end: min(dts.time_end, ats.time_end - estimated_duration_s),
                    };

                    //
                    //  |     dts     |             (depart timeslot)
                    //   ----->       ----->        (flight time)
                    //      |    ats            |   (target timeslot)
                    //         | actual ats |
                    // The actual target_timeslot is the timeslot within which target is possible
                    //  given a origin from the actual depart timeslot.
                    let target_timeslot = Timeslot {
                        time_start: max(
                            ats.time_start,
                            origin_timeslot.time_start + estimated_duration_s,
                        ),
                        time_end: min(
                            ats.time_end,
                            origin_timeslot.time_end + estimated_duration_s,
                        ),
                    };

                    pairs.push(TimeslotPair {
                        origin_vertiport_id: origin_vertiport_id.to_string(),
                        origin_vertipad_id: origin_vertipad_id.clone(),
                        origin_timeslot,
                        target_vertiport_id: target_vertiport_id.to_string(),
                        target_vertipad_id: target_vertipad_id.clone(),
                        target_timeslot,
                        path,
                        distance_meters,
                    });
                }
            }
        }
    }

    // Sort available options by shortest distance first
    pairs.sort_by(
        |a, b| match a.distance_meters.partial_cmp(&b.distance_meters) {
            Some(ord) => ord,
            None => {
                router_error!(
                    "(get_vertipad_timeslot_pairs) Could not compare distances: {}, {}",
                    a.distance_meters,
                    b.distance_meters
                );
                std::cmp::Ordering::Equal
            }
        },
    );

    Ok(pairs)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grpc::client::get_clients;
    use crate::router::vehicle::estimate_flight_time_seconds;
    use chrono::DateTime;
    use uuid::Uuid;

    #[tokio::test]
    #[cfg(feature = "stub_backends")]
    async fn ut_get_vertipad_pairs_no_overlap() {
        let origin_vertiport_id: String = Uuid::new_v4().to_string();
        let target_vertiport_id: String = Uuid::new_v4().to_string();
        let origin_vertipad_id: String = Uuid::new_v4().to_string();
        let target_vertipad_id: String = Uuid::new_v4().to_string();
        let clients = get_clients().await;

        //
        // CASE 1: No overlap, even leaving at the last minute of the origin window
        //                          |-----v2----|
        //             >>>>>>>>>>x
        // |-----v1----|
        // |           |            |           |
        // 3           6            10          13

        let origin_start = DateTime::from_str("2021-01-01T03:00:00Z").unwrap();
        let origin_end = DateTime::from_str("2021-01-01T06:00:00Z").unwrap();
        let origin_vertipads = HashMap::from([(
            origin_vertipad_id.clone(),
            vec![Timeslot {
                time_start: origin_start,
                time_end: origin_end,
            }],
        )]);

        let target_vertipads = HashMap::from([(
            target_vertipad_id.clone(),
            vec![Timeslot {
                time_start: DateTime::from_str("2021-01-01T10:00:00Z").unwrap(),
                time_end: DateTime::from_str("2021-01-01T13:00:00Z").unwrap(),
            }],
        )]);

        let pairs = get_vertipad_timeslot_pairs(
            &origin_vertiport_id,
            &target_vertiport_id,
            origin_vertipads,
            target_vertipads,
            &clients,
        )
        .await
        .unwrap();

        assert!(pairs.is_empty());
    }

    #[tokio::test]
    #[cfg(feature = "stub_backends")]
    async fn ut_get_vertipad_pairs_no_overlap_target_lead() {
        let origin_vertiport_id: String = Uuid::new_v4().to_string();
        let target_vertiport_id: String = Uuid::new_v4().to_string();
        let origin_vertipad_id: String = Uuid::new_v4().to_string();
        let target_vertipad_id: String = Uuid::new_v4().to_string();
        let clients = get_clients().await;

        //
        // No overlap, target window is earlier
        //             |-----v1----|
        //
        // |-----v2----|
        // |           |           |           |
        // 3           6           10          13

        let origin_start = DateTime::from_str("2021-01-01T06:00:00Z").unwrap();
        let origin_end = DateTime::from_str("2021-01-01T10:00:00Z").unwrap();
        let origin_vertipads = HashMap::from([(
            origin_vertipad_id.clone(),
            vec![Timeslot {
                time_start: origin_start,
                time_end: origin_end,
            }],
        )]);

        let target_vertipads = HashMap::from([(
            target_vertipad_id.clone(),
            vec![Timeslot {
                time_start: DateTime::from_str("2021-01-01T03:00:00Z").unwrap(),
                time_end: DateTime::from_str("2021-01-01T06:00:00Z").unwrap(),
            }],
        )]);

        let pairs = get_vertipad_timeslot_pairs(
            &origin_vertiport_id,
            &target_vertiport_id,
            origin_vertipads,
            target_vertipads,
            &clients,
        )
        .await
        .unwrap();

        println!("{:?}", pairs);
        assert!(pairs.is_empty());
    }

    #[tokio::test]
    #[cfg(feature = "stub_backends")]
    async fn ut_get_vertipad_pairs_some_overlap() {
        let origin_vertiport_id: String = Uuid::new_v4().to_string();
        let target_vertiport_id: String = Uuid::new_v4().to_string();
        let origin_vertipad_id: String = Uuid::new_v4().to_string();
        let target_vertipad_id: String = Uuid::new_v4().to_string();
        let clients = get_clients().await;

        //
        // Some overlap
        //             |-----v2----|
        //             >>>>> Leave at end of depart window
        //           >>>>> Middle case
        //         >>>>> Arrive at start of target window
        // |-----v1----|
        // |           |           |
        // 3           6           9

        let origin_start = DateTime::from_str("2021-01-01T03:00:00Z").unwrap();
        let origin_end = DateTime::from_str("2021-01-01T06:00:00Z").unwrap();
        let origin_vertipads = HashMap::from([(
            origin_vertipad_id.clone(),
            vec![Timeslot {
                time_start: origin_start,
                time_end: origin_end,
            }],
        )]);

        let target_start = DateTime::from_str("2021-01-01T06:00:00Z").unwrap();
        let target_end = DateTime::from_str("2021-01-01T09:00:00Z").unwrap();
        let target_vertipads = HashMap::from([(
            target_vertipad_id.clone(),
            vec![Timeslot {
                time_start: target_start,
                time_end: target_end,
            }],
        )]);

        let pairs = get_vertipad_timeslot_pairs(
            &origin_vertiport_id,
            &target_vertiport_id,
            origin_vertipads,
            target_vertipads,
            &clients,
        )
        .await
        .unwrap();

        assert_eq!(pairs.len(), 1);
        let pair = pairs.last().unwrap();
        let flight_duration = estimate_flight_time_seconds(&pair.distance_meters).unwrap();

        assert_eq!(pair.origin_vertipad_id, origin_vertipad_id);
        assert_eq!(pair.target_vertipad_id, target_vertipad_id);
        assert_eq!(
            pair.origin_timeslot.time_start,
            target_start - flight_duration
        );

        assert_eq!(pair.origin_timeslot.time_end, origin_end);
        assert_eq!(pair.target_timeslot.time_start, target_start);
        assert_eq!(pair.target_timeslot.time_end, origin_end + flight_duration);
    }

    #[tokio::test]
    #[cfg(feature = "stub_backends")]
    async fn ut_get_vertipad_pairs_overlap_nested() {
        let origin_vertiport_id: String = Uuid::new_v4().to_string();
        let target_vertiport_id: String = Uuid::new_v4().to_string();
        let origin_vertipad_id: String = Uuid::new_v4().to_string();
        let target_vertipad_id: String = Uuid::new_v4().to_string();
        let clients = get_clients().await;
        //
        // Some overlap
        //       |-----v2---|
        //                >>> Arrive at end of target window
        //         >>> Middle case
        //     >>> Arrive at start of target window
        // |-----v1----------------|
        // |           |           |
        // 3           6           9

        let origin_start = DateTime::from_str("2021-01-01T03:00:00Z").unwrap();
        let origin_end = DateTime::from_str("2021-01-01T09:00:00Z").unwrap();
        let origin_vertipads = HashMap::from([(
            origin_vertipad_id.clone(),
            vec![Timeslot {
                time_start: origin_start,
                time_end: origin_end,
            }],
        )]);

        let target_start = DateTime::from_str("2021-01-01T05:00:00Z").unwrap();
        let target_end = DateTime::from_str("2021-01-01T07:00:00Z").unwrap();
        let target_vertipads = HashMap::from([(
            target_vertipad_id.clone(),
            vec![Timeslot {
                time_start: target_start,
                time_end: target_end,
            }],
        )]);

        let pairs = get_vertipad_timeslot_pairs(
            &origin_vertiport_id,
            &target_vertiport_id,
            origin_vertipads,
            target_vertipads,
            &clients,
        )
        .await
        .unwrap();

        assert_eq!(pairs.len(), 1);
        let pair = pairs.last().unwrap();
        let flight_duration = estimate_flight_time_seconds(&pair.distance_meters).unwrap();

        assert_eq!(pair.origin_vertipad_id, origin_vertipad_id);
        assert_eq!(pair.target_vertipad_id, target_vertipad_id);
        assert_eq!(
            pair.origin_timeslot.time_start,
            target_start - flight_duration
        );
        assert_eq!(pair.origin_timeslot.time_end, target_end - flight_duration);
        assert_eq!(pair.target_timeslot.time_start, target_start);
        assert_eq!(pair.target_timeslot.time_end, target_end);
    }

    #[tokio::test]
    #[cfg(feature = "stub_backends")]
    async fn ut_get_vertipad_pairs_overlap_target_window_lead() {
        let origin_vertiport_id: String = Uuid::new_v4().to_string();
        let target_vertiport_id: String = Uuid::new_v4().to_string();
        let origin_vertipad_id: String = Uuid::new_v4().to_string();
        let target_vertipad_id: String = Uuid::new_v4().to_string();
        let clients = get_clients().await;

        //
        // Some overlap, target window leads
        // |-------v2-----|
        //             >>>
        //             |-----------|
        // |           |           |
        // 3           6           9

        let origin_start = DateTime::from_str("2021-01-01T06:00:00Z").unwrap();
        let origin_end = DateTime::from_str("2021-01-01T09:00:00Z").unwrap();
        let origin_vertipads = HashMap::from([(
            origin_vertipad_id.clone(),
            vec![Timeslot {
                time_start: origin_start,
                time_end: origin_end,
            }],
        )]);

        let target_start = DateTime::from_str("2021-01-01T03:00:00Z").unwrap();
        let target_end = DateTime::from_str("2021-01-01T07:00:00Z").unwrap();
        let target_vertipads = HashMap::from([(
            target_vertipad_id.clone(),
            vec![Timeslot {
                time_start: target_start,
                time_end: target_end,
            }],
        )]);

        let pairs = get_vertipad_timeslot_pairs(
            &origin_vertiport_id,
            &target_vertiport_id,
            origin_vertipads,
            target_vertipads,
            &clients,
        )
        .await
        .unwrap();

        assert_eq!(pairs.len(), 1);
        let pair = pairs.last().unwrap();
        let flight_duration = estimate_flight_time_seconds(&pair.distance_meters).unwrap();

        assert_eq!(pair.origin_vertipad_id, origin_vertipad_id);
        assert_eq!(pair.target_vertipad_id, target_vertipad_id);
        assert_eq!(pair.origin_timeslot.time_start, origin_start);
        assert_eq!(pair.origin_timeslot.time_end, target_end - flight_duration);
        assert_eq!(
            pair.target_timeslot.time_start,
            origin_start + flight_duration
        );
        assert_eq!(pair.target_timeslot.time_end, target_end);
    }

    #[tokio::test]
    #[cfg(feature = "stub_backends")]
    async fn ut_get_vertipad_pairs_overlap_multiple() {
        let origin_vertiport_id: String = Uuid::new_v4().to_string();
        let target_vertiport_id: String = Uuid::new_v4().to_string();
        let origin_vertipad_id: String = Uuid::new_v4().to_string();
        let target_vertipad_id: String = Uuid::new_v4().to_string();
        let clients = get_clients().await;

        //
        // Some overlap
        //       |-----v2-p1--|    |-----v2-p2--|
        //
        // |-----v1----------------|
        // |           |           |
        // 3           6           9

        let origin_start = DateTime::from_str("2021-01-01T03:00:00Z").unwrap();
        let origin_end = DateTime::from_str("2021-01-01T09:00:00Z").unwrap();
        let origin_vertipads = HashMap::from([(
            origin_vertipad_id.clone(),
            vec![Timeslot {
                time_start: origin_start,
                time_end: origin_end,
            }],
        )]);

        let target_timeslot_1 = Timeslot {
            time_start: DateTime::from_str("2021-01-01T05:00:00Z").unwrap(),
            time_end: DateTime::from_str("2021-01-01T07:00:00Z").unwrap(),
        };

        let target_timeslot_2 = Timeslot {
            time_start: DateTime::from_str("2021-01-01T09:00:00Z").unwrap(),
            time_end: DateTime::from_str("2021-01-01T10:00:00Z").unwrap(),
        };

        let target_vertipads = HashMap::from([(
            target_vertipad_id.clone(),
            vec![target_timeslot_1, target_timeslot_2],
        )]);

        let pairs = get_vertipad_timeslot_pairs(
            &origin_vertiport_id,
            &target_vertiport_id,
            origin_vertipads,
            target_vertipads,
            &clients,
        )
        .await
        .unwrap();

        assert_eq!(pairs.len(), 2);

        {
            let pair = pairs[0].clone();
            let target_timeslot = target_timeslot_1;
            assert_eq!(pair.origin_vertipad_id, origin_vertipad_id);
            assert_eq!(pair.target_vertipad_id, target_vertipad_id);

            let flight_duration = estimate_flight_time_seconds(&pair.distance_meters).unwrap();
            assert_eq!(
                pair.origin_timeslot.time_start,
                target_timeslot.time_start - flight_duration
            );

            assert_eq!(
                pair.origin_timeslot.time_end,
                target_timeslot.time_end - flight_duration
            );

            assert_eq!(pair.target_timeslot.time_start, target_timeslot.time_start);
            assert_eq!(pair.target_timeslot.time_end, target_timeslot.time_end);
        }

        {
            let pair = pairs[1].clone();
            let target_timeslot = target_timeslot_2;
            assert_eq!(pair.origin_vertipad_id, origin_vertipad_id);
            assert_eq!(pair.target_vertipad_id, target_vertipad_id);

            let flight_duration = estimate_flight_time_seconds(&pair.distance_meters).unwrap();
            assert_eq!(
                pair.origin_timeslot.time_start,
                target_timeslot.time_start - flight_duration
            );

            assert_eq!(pair.origin_timeslot.time_end, origin_end);

            assert_eq!(pair.target_timeslot.time_start, target_timeslot.time_start);
            assert_eq!(pair.target_timeslot.time_end, origin_end + flight_duration);
        }
    }
}