Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

52.3 KB
Raw Blame
use super::*;
use chrono::{TimeZone, Utc};
use wiremock::{
    Mock, MockServer, ResponseTemplate,
    matchers::{body_partial_json, header, method, path, query_param},
};

mod mutations;
mod sync;

pub(super) fn target() -> ProviderCalendarTarget {
    let link_id = Uuid::now_v7();
    ProviderCalendarTarget {
        binding: Some(CalendarGrantBinding {
            link_id,
            sync_generation: 2,
            grant_generation: 3,
        }),
        provider: CalendarProvider::Outlook,
        owner_id: "macro|[email protected]".into(),
        email_link_id: link_id,
        account_id: Uuid::now_v7(),
        calendar_id: Uuid::now_v7(),
        provider_calendar_id: "calendar".into(),
        observed_access_role: Some("owner".into()),
        is_read_only: false,
        range: OccurrenceRange {
            starts_at: Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2027, 1, 1, 0, 0, 0).unwrap(),
            start_date: "2026-01-01".parse().unwrap(),
            end_date: "2027-01-01".parse().unwrap(),
        },
    }
}
pub(super) fn event(id: &str) -> Value {
    json!({"id":id,"@odata.etag":"W/\"1\"","iCalUId":format!("{id}@outlook"),"subject":"Meeting","type":"singleInstance","createdDateTime":"2026-01-01T10:00:00Z","lastModifiedDateTime":"2026-10-01T10:00:00Z","originalStartTimeZone":"Pacific Standard Time","start":{"dateTime":"2026-11-02T17:00:00.0000000","timeZone":"UTC"},"end":{"dateTime":"2026-11-02T18:00:00.0000000","timeZone":"UTC"},"isAllDay":false,"attendees":[]})
}
/// One instance as `GET /me/events/{id}/instances` returns it for `request`.
/// With a `$select`, Graph returns only the named properties, besides `id`,
/// annotations and what `$expand` names. Without one it returns its default
/// properties, which leave out `originalStart`: every stored occurrence of
/// the dev Outlook mailbox's series has no original start, which only
/// happens when Graph sends none.
pub(super) fn as_graph_returns(instance: &Value, request: &wiremock::Request) -> Value {
    let query: Vec<(String, String)> = request.url.query_pairs().into_owned().collect();
    let select: Option<Vec<&str>> = query
        .iter()
        .find(|(key, _)| key == "$select")
        .map(|(_, value)| value.split(',').collect());
    let expanded = query
        .iter()
        .any(|(key, value)| key == "$expand" && value.starts_with("singleValueExtendedProperties"));
    let returned = instance
        .as_object()
        .unwrap()
        .iter()
        .filter(|(key, _)| match key.as_str() {
            "id" => true,
            "singleValueExtendedProperties" => expanded,
            key if key.starts_with("@odata.") => true,
            key => match &select {
                Some(names) => names.contains(&key),
                None => key != "originalStart",
            },
        })
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect();
    Value::Object(returned)
}

/// A series' `instances` endpoint that answers as Graph does (see
/// [`as_graph_returns`]).
pub(super) struct Instances(pub(super) Vec<Value>);

impl wiremock::Respond for Instances {
    fn respond(&self, request: &wiremock::Request) -> ResponseTemplate {
        let value: Vec<_> = self
            .0
            .iter()
            .map(|instance| as_graph_returns(instance, request))
            .collect();
        ResponseTemplate::new(200).set_body_json(json!({ "value": value }))
    }
}

/// An instance of Graph's documented weekly "Review strategy for Q3" series
/// (List instances, v1.0), with every default property of a v1.0 `event`.
/// `day` is its date, `original_day` the date of the slot it fills.
pub(super) fn documented_instance(id: &str, kind: &str, day: &str, original_day: &str) -> Value {
    let mut value = json!({
        "@odata.etag":"W/\"x3IAvB5fbUWf4XNcBFLNUwAAKuA3yQ==\"",
        "id":id,
        "createdDateTime":"2019-03-28T17:08:14.3474405Z",
        "lastModifiedDateTime":"2019-04-02T20:17:49.6339342Z",
        "changeKey":"x3IAvB5fbUWf4XNcBFLNUwAAKuA3yQ==",
        "categories":[],
        "transactionId":null,
        "originalStartTimeZone":"Pacific Standard Time",
        "originalEndTimeZone":"Pacific Standard Time",
        "iCalUId":"040000008200E00074C5B7101A82E00807E3040F2C5F84B3B5E5D401000000000000000010000000F4A8D0BB2AA6DC4FA5B57C6A0DBF2E3A",
        "reminderMinutesBeforeStart":15,
        "isReminderOn":true,
        "hasAttachments":false,
        "subject":"Review strategy for Q3",
        "bodyPreview":"",
        "importance":"normal",
        "sensitivity":"normal",
    });
    let rest = json!({
        "originalStart":format!("{original_day}T20:30:00Z"),
        "isAllDay":false,
        "isCancelled":false,
        "isOrganizer":false,
        "responseRequested":true,
        "seriesMasterId":"AAMkAGUzYRgWAAA=",
        "showAs":"busy",
        "type":kind,
        "webLink":format!("https://outlook.office365.com/owa/?itemid={id}&exvsurl=1&path=/calendar/item"),
        "onlineMeetingUrl":null,
        "isOnlineMeeting":false,
        "onlineMeetingProvider":"unknown",
        "allowNewTimeProposals":true,
        "isDraft":false,
        "hideAttendees":false,
        "recurrence":null,
        "onlineMeeting":null,
        "responseStatus":{"response":"accepted","time":"2019-04-02T20:20:00Z"},
        "body":{"contentType":"html","content":"<html><body><p>Quarterly review</p></body></html>"},
        "start":{"dateTime":format!("{day}T20:30:00.0000000"),"timeZone":"UTC"},
        "end":{"dateTime":format!("{day}T21:00:00.0000000"),"timeZone":"UTC"},
        "location":{"displayName":"Conference room","locationType":"default","uniqueIdType":"unknown"},
        "locations":[{"displayName":"Conference room","locationType":"default","uniqueIdType":"unknown"}],
        "attendees":[{
            "type":"required",
            "status":{"response":"accepted","time":"2019-04-02T20:20:00Z"},
            "emailAddress":{"name":"Ada","address":"[email protected]"}
        }],
        "organizer":{"emailAddress":{"name":"Olivia","address":"[email protected]"}}
    });
    for (key, property) in rest.as_object().unwrap() {
        value[key.as_str()] = property.clone();
    }
    value
}

/// The series of Graph's documented List instances example, with the
/// occurrences and the exception that response lists: its 15 April meeting
/// moved to the 16th, with its own details.
pub(super) fn documented_series() -> (Value, Vec<Value>) {
    let mut master = documented_instance(
        "AAMkAGUzYRgWAAA=",
        "seriesMaster",
        "2019-04-08",
        "2019-04-08",
    );
    for property in ["originalStart", "seriesMasterId"] {
        master.as_object_mut().unwrap().remove(property);
    }
    master["recurrence"] = json!({
        "pattern":{"type":"weekly","interval":1,"month":0,"dayOfMonth":0,"daysOfWeek":["monday"],"firstDayOfWeek":"sunday","index":"first"},
        "range":{"type":"endDate","startDate":"2019-04-08","endDate":"2019-04-29","recurrenceTimeZone":"Pacific Standard Time","numberOfOccurrences":0}
    });
    let mut moved = documented_instance(
        "AAMkAGUzYAgI1sE1TatAAEYAAAAAlNFb2CNPe0ucP9you",
        "exception",
        "2019-04-16",
        "2019-04-15",
    );
    moved["subject"] = json!("Review strategy for Q3 (moved)");
    moved["bodyPreview"] = json!("Changing meeting from 4/15 to 4/16.");
    moved["body"]["content"] =
        json!("<html><body><p>Changing meeting from 4/15 to 4/16.</p></body></html>");
    moved["location"]["displayName"] = json!("Board room");
    moved["sensitivity"] = json!("private");
    moved["showAs"] = json!("tentative");
    moved["isReminderOn"] = json!(false);
    moved["lastModifiedDateTime"] = json!("2019-04-03T09:12:00.1234567Z");
    moved["attendees"][0]["emailAddress"] = json!({"name":"Grace","address":"[email protected]"});
    let instances = vec![
        moved,
        documented_instance(
            "AAMkAGUzYAgI1ru1JMcAAEYAAAAAlNFb2CNPe0ucP9you",
            "occurrence",
            "2019-04-08",
            "2019-04-08",
        ),
        documented_instance(
            "AAMkAGUzYAgI1sa1do_AAEYAAAAAlNFb2CNPe0ucP9you",
            "occurrence",
            "2019-04-22",
            "2019-04-22",
        ),
        documented_instance(
            "AAMkAGUzYAgI1sw1n3PAAEYAAAAAlNFb2CNPe0ucP9you",
            "occurrence",
            "2019-04-29",
            "2019-04-29",
        ),
    ];
    (master, instances)
}

/// The window of Graph's documented List instances request.
pub(super) fn april_2019() -> ProviderCalendarTarget {
    let mut target = target();
    target.range = OccurrenceRange {
        starts_at: Utc.with_ymd_and_hms(2019, 4, 8, 9, 0, 0).unwrap(),
        ends_at: Utc.with_ymd_and_hms(2019, 4, 30, 9, 0, 0).unwrap(),
        start_date: "2019-04-08".parse().unwrap(),
        end_date: "2019-04-30".parse().unwrap(),
    };
    target
}

/// `GET /me/mailboxSettings` as Graph documents it, with `time_zone` as the
/// mailbox's zone, or without one when it is `None`. Its working hours keep a
/// zone of their own.
pub(super) fn mailbox_settings(time_zone: Option<&str>) -> Value {
    let mut settings = json!({
        "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#Me/mailboxSettings",
        "archiveFolder":"AAMkAGI2TGuLAAA=",
        "automaticRepliesSetting":{
            "status":"disabled","externalAudience":"all",
            "scheduledStartDateTime":{"dateTime":"2026-11-04T08:00:00.0000000","timeZone":"UTC"},
            "scheduledEndDateTime":{"dateTime":"2026-11-05T08:00:00.0000000","timeZone":"UTC"},
            "internalReplyMessage":"","externalReplyMessage":""
        },
        "timeZone":time_zone,
        "language":{"locale":"en-US","displayName":"English (United States)"},
        "workingHours":{
            "daysOfWeek":["monday","tuesday","wednesday","thursday","friday"],
            "startTime":"08:00:00.0000000","endTime":"17:00:00.0000000",
            "timeZone":{"name":"Pacific Standard Time"}
        },
        "userPurpose":{"value":"user"},
        "dateFormat":"MM/dd/yyyy","timeFormat":"hh:mm tt",
        "delegateMeetingMessageDeliveryOptions":"sendToDelegateOnly"
    });
    if time_zone.is_none() {
        settings.as_object_mut().unwrap().remove("timeZone");
    }
    settings
}
/// The mailbox's default calendar, as `GET /me/calendars` lists it.
pub(super) fn default_calendar(id: &str) -> Value {
    json!({
        "id":id,"name":"Calendar","color":"auto","hexColor":"","isDefaultCalendar":true,
        "changeKey":"nfZyf7VcrEKLNoU37KWlkQAAA0x0+w==","canShare":true,"canViewPrivateItems":true,
        "isSharedWithMe":false,"canEdit":true,
        "allowedOnlineMeetingProviders":["teamsForBusiness"],"defaultOnlineMeetingProvider":"teamsForBusiness",
        "isTallyingResponses":true,"isRemovable":false,
        "owner":{"name":"Olivia","address":"[email protected]"}
    })
}
pub(super) async fn setup() -> (MockServer, OutlookApiClientRepository) {
    let server = MockServer::start().await;
    let api = OutlookApiClientRepository::for_test(&format!("{}/v1.0/", server.uri()));
    (server, api)
}
async fn serve_event(server: &MockServer, id: &str) {
    Mock::given(method("GET"))
        .and(path(format!("/v1.0/me/calendars/calendar/events/{id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(event(id)))
        .mount(server)
        .await;
}

#[tokio::test]
async fn calendar_cursor_never_sends_bearer_outside_graph_root() {
    let (server, api) = setup().await;
    for cursor in [
        "https://attacker.invalid/v1.0/me/calendarView/delta".into(),
        format!("{}/outside", server.uri()),
    ] {
        assert!(
            api.calendar_page("secret", &target(), true, Some(&cursor))
                .await
                .is_err()
        );
    }
    assert!(server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn primary_page_preserves_tombstones_and_terminal_cursor_for_durable_reconciliation() {
    let (server, api) = setup().await;
    let old = format!(
        "{}/v1.0/me/calendarView/delta?$deltatoken=old",
        server.uri()
    );
    let end = format!(
        "{}/v1.0/me/calendarView/delta?$deltatoken=complete%2Bopaque",
        server.uri()
    );
    Mock::given(method("GET")).and(path("/v1.0/me/calendarView/delta")).and(query_param("$deltatoken","old"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"value":[{"id":"old-instance","@removed":{"reason":"deleted"}},{"id":"new-instance","seriesMasterId":"series"}],"@odata.deltaLink":end}))).expect(1).mount(&server).await;
    let page = api
        .calendar_page("token", &target(), true, Some(&old))
        .await
        .unwrap();
    assert_eq!(page.removed, vec!["old-instance"]);
    assert_eq!(page.members, vec![("new-instance".into(), "series".into())]);
    assert_eq!(page.delta, Some(end));
}

#[tokio::test]
async fn secondary_calendars_use_complete_v1_views_and_follow_every_page() {
    let (server, api) = setup().await;
    let next = format!(
        "{}/v1.0/me/calendars/calendar/calendarView?$skiptoken=A%2BB%3D",
        server.uri()
    );
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/calendarView"))
        .and(query_param("$top", "1000"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"value":[{"id":"one"}],"@odata.nextLink":next})),
        )
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/calendarView"))
        .and(query_param("$skiptoken", "A+B="))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"value":[{"id":"two"}]})))
        .expect(1)
        .mount(&server)
        .await;
    let first = api
        .calendar_page("token", &target(), false, None)
        .await
        .unwrap();
    assert_eq!(first.members, vec![("one".into(), "one".into())]);
    assert_eq!(first.next.as_deref(), Some(next.as_str()));
    let last = api
        .calendar_page("token", &target(), false, first.next.as_deref())
        .await
        .unwrap();
    assert_eq!(last.members, vec![("two".into(), "two".into())]);
    assert!(last.next.is_none());
    assert!(last.delta.is_none());
}

/// Discover the calendars of a mailbox whose settings name `time_zone`.
async fn discover(time_zone: Option<&str>) -> OutlookDiscovery {
    let (server, api) = setup().await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/mailboxSettings"))
        .respond_with(ResponseTemplate::new(200).set_body_json(mailbox_settings(time_zone)))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#me/calendars",
            "value":[default_calendar("AAMkCalendar")],
        })))
        .mount(&server)
        .await;
    match api.calendars("token", target().binding.unwrap()).await {
        Ok(discovery) => discovery,
        Err(_) => panic!("a mailbox in {time_zone:?} fails discovery"),
    }
}

#[tokio::test]
async fn calendars_carry_the_iana_zone_of_the_mailbox() {
    for (named, iana) in [
        (Some("Pacific Standard Time"), "America/Los_Angeles"),
        (Some("America/Los_Angeles"), "America/Los_Angeles"),
        (None, "Etc/UTC"),
    ] {
        let discovery = discover(named).await;
        assert_eq!(
            discovery.calendars[0].calendar.time_zone.as_deref(),
            Some(iana),
            "{named:?}"
        );
        assert_eq!(discovery.unmapped_time_zone, None, "{named:?}");
    }
}

#[tokio::test]
async fn a_mailbox_time_zone_macro_cannot_map_leaves_its_calendars_without_one() {
    for named in [
        "tzone://Microsoft/Custom",
        "Atlantis Standard Time",
        "",
        // In CLDR 49, but held out until Macro's tz data has its 2026 rules.
        "British Columbia Standard Time",
    ] {
        let discovery = discover(Some(named)).await;
        assert_eq!(discovery.calendars.len(), 1, "{named:?}");
        assert_eq!(
            discovery.calendars[0].calendar.time_zone, None,
            "{named:?} is unknown, not UTC"
        );
        assert_eq!(
            discovery.unmapped_time_zone.as_deref(),
            Some(named),
            "{named:?}"
        );
    }
}

#[test]
fn windows_zones_and_moved_exceptions_preserve_the_original_occurrence() {
    let mut master = event("master");
    master["type"] = json!("seriesMaster");
    master["recurrence"] = json!({"pattern":{"type":"weekly","interval":1,"daysOfWeek":["monday"],"firstDayOfWeek":"monday"},"range":{"type":"noEnd","startDate":"2026-11-02","recurrenceTimeZone":"Pacific Standard Time"}});
    let mut exception = event("instance");
    exception["type"] = json!("exception");
    exception["originalStart"] = json!("2026-11-02T17:00:00Z");
    exception["subject"] = json!("Moved meeting");
    exception["start"]["dateTime"] = json!("2026-11-03T18:00:00");
    exception["end"]["dateTime"] = json!("2026-11-03T19:00:00");
    let upsert = normalize::projection(&target(), master, vec![exception])
        .unwrap()
        .upsert;
    assert_eq!(
        upsert.occurrences[0].recurrence_id.as_deref(),
        Some("2026-11-02T17:00:00+00:00")
    );
    assert_eq!(upsert.overrides[0].title.as_deref(), Some("Moved meeting"));
    assert!(
        matches!(upsert.event.time,EventTime::Timed{time_zone:Some(ref z),..} if z=="America/Los_Angeles")
    );
    let time = EventTime::Timed {
        starts_at: "2026-03-09T16:00:00Z".parse().unwrap(),
        ends_at: "2026-03-09T17:00:00Z".parse().unwrap(),
        time_zone: Some("America/Los_Angeles".into()),
    };
    assert_eq!(
        normalize::time_body(&time).unwrap().0["dateTime"],
        "2026-03-09T09:00:00"
    );
}

#[test]
fn all_day_utc_responses_keep_local_dates_across_dst() {
    let mut v = event("all-day");
    v["isAllDay"] = json!(true);
    v["start"]["dateTime"] = json!("2026-03-08T08:00:00");
    v["end"]["dateTime"] = json!("2026-03-09T07:00:00");
    assert_eq!(
        normalize::event_time(&v).unwrap(),
        EventTime::AllDay {
            start_date: "2026-03-08".parse().unwrap(),
            end_date: "2026-03-09".parse().unwrap()
        }
    );
}

#[test]
fn recurrence_rejects_lossy_rules_instead_of_dropping_parts() {
    let time = normalize::event_time(&event("e")).unwrap();
    for rule in [
        vec!["RRULE:FREQ=DAILY;BYHOUR=9,17".into()],
        vec!["RRULE:FREQ=MONTHLY;BYMONTHDAY=1,15".into()],
        vec!["RRULE:FREQ=WEEKLY".into(), "EXDATE:20261201T170000Z".into()],
    ] {
        assert!(recurrence::to_graph(&rule, &time).is_err());
    }
    let pattern =
        recurrence::to_graph(&["RRULE:FREQ=MONTHLY;BYDAY=-1MO;COUNT=12".into()], &time).unwrap();
    assert_eq!(pattern["pattern"]["type"], "relativeMonthly");
    assert_eq!(pattern["pattern"]["index"], "last");
    assert_eq!(pattern["range"]["numberOfOccurrences"], 12);
}

#[tokio::test]
async fn edits_use_etags_and_keep_unrequested_provider_fields_untouched() {
    let (server, api) = setup().await;
    serve_event(&server, "event").await;
    Mock::given(method("PATCH"))
        .and(path("/v1.0/me/events/event"))
        .and(header("if-match", "W/\"1\""))
        .and(header("prefer", "IdType=\"ImmutableId\""))
        .and(body_partial_json(json!({"subject":"Changed"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(event("event")))
        .expect(1)
        .mount(&server)
        .await;
    api.update_event(
        "token",
        &target(),
        "event",
        &CalendarEventPatch {
            title: Some("Changed".into()),
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let requests = server.received_requests().await.unwrap();
    let patch = requests
        .iter()
        .find(|r| r.method.as_str() == "PATCH")
        .unwrap();
    assert_eq!(
        serde_json::from_slice::<Value>(&patch.body).unwrap(),
        json!({"subject":"Changed"})
    );
}

#[test]
fn provider_restrictions_are_explicit_and_extra_popup_reminders_round_trip() {
    let mut current = event("e");
    current["isOnlineMeeting"] = json!(true);
    assert!(
        patch_body(
            &CalendarEventPatch {
                conference: Some(ConferenceChange::Removed),
                ..Default::default()
            },
            Some(&current)
        )
        .is_err()
    );
    let reminders = EventReminders {
        use_default: false,
        overrides: vec![
            EventReminderOverride {
                method: "popup".into(),
                minutes: 10,
            },
            EventReminderOverride {
                method: "popup".into(),
                minutes: 30,
            },
        ],
    };
    let body = patch_body(
        &CalendarEventPatch {
            reminders: Some(reminders.clone()),
            ..Default::default()
        },
        Some(&current),
    )
    .unwrap();
    current["singleValueExtendedProperties"] = body["singleValueExtendedProperties"].clone();
    current["isReminderOn"] = body["isReminderOn"].clone();
    current["reminderMinutesBeforeStart"] = body["reminderMinutesBeforeStart"].clone();
    assert_eq!(
        normalize::projection(&target(), current, vec![])
            .unwrap()
            .upsert
            .event
            .reminders,
        reminders
    );
    assert_eq!(body["reminderMinutesBeforeStart"], 10);
    let email_reminder = patch_body(
        &CalendarEventPatch {
            reminders: Some(EventReminders {
                use_default: false,
                overrides: vec![EventReminderOverride {
                    method: "email".into(),
                    minutes: 10,
                }],
            }),
            ..Default::default()
        },
        None,
    )
    .unwrap();
    assert_eq!(email_reminder["isReminderOn"], false);
    let mut email_event = event("email-reminder");
    email_event["isReminderOn"] = email_reminder["isReminderOn"].clone();
    email_event["singleValueExtendedProperties"] =
        email_reminder["singleValueExtendedProperties"].clone();
    let restored = normalize::projection(&target(), email_event, vec![])
        .unwrap()
        .upsert;
    assert_eq!(restored.event.reminders.overrides[0].method, "email");
}

#[tokio::test]
async fn retrying_an_acknowledged_creation_adopts_the_assigned_id_without_reinviting() {
    let (server, api) = setup().await;
    let target = target();
    let key = Uuid::now_v7();
    let correlation = creation_provider_id(key, &target.owner_id);
    let mut existing = event("microsoft-assigned-id");
    existing["transactionId"] = json!(correlation);
    let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let counter = reads.clone();
    let found = existing.clone();
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/events"))
        .respond_with(move |_: &wiremock::Request| {
            ResponseTemplate::new(200).set_body_json(
                if counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
                    json!({"value":[]})
                } else {
                    json!({"value":[found.clone()]})
                },
            )
        })
        .expect(2)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v1.0/me/calendars/calendar/events"))
        .and(body_partial_json(json!({"transactionId":correlation})))
        .respond_with(ResponseTemplate::new(201).set_body_json(existing.clone()))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path(
            "/v1.0/me/calendars/calendar/events/microsoft-assigned-id",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(existing))
        .expect(2)
        .mount(&server)
        .await;
    let draft = CalendarEventDraft {
        idempotency_key: Some(key),
        title: "Booking".into(),
        description: None,
        location: None,
        time: normalize::event_time(&event("e")).unwrap(),
        attendees: vec![],
        recurrence_lines: vec![],
        visibility: None,
        transparency: None,
        reminders: None,
        conference: None,
        out_of_office: None,
        guest_policy: None,
    };
    let first = api.create_event("token", &target, &draft).await.unwrap();
    let replay = api.create_event("token", &target, &draft).await.unwrap();
    assert_eq!(
        first.source.details().provider_event_id,
        "microsoft-assigned-id"
    );
    assert_eq!(
        first.source.details().provider_event_id,
        replay.source.details().provider_event_id
    );
}

#[tokio::test]
async fn cancelling_an_unacknowledged_booking_resolves_its_provider_assigned_id() {
    let (server, api) = setup().await;
    let target = target();
    let key = Uuid::now_v7();
    let correlation = creation_provider_id(key, &target.owner_id);
    let mut existing = event("assigned");
    existing["transactionId"] = json!(correlation);
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/events"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"value":[existing]})))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("DELETE"))
        .and(path("/v1.0/me/events/assigned"))
        .and(header("if-match", "W/\"1\""))
        .respond_with(ResponseTemplate::new(204))
        .expect(1)
        .mount(&server)
        .await;
    assert_eq!(
        api.delete_created_event("token", &target, key)
            .await
            .unwrap(),
        vec!["assigned"]
    );
}

#[test]
fn native_reminder_edits_supersede_macro_extra_reminders() {
    let mut current = event("e");
    current["isReminderOn"] = json!(true);
    current["reminderMinutesBeforeStart"] = json!(60);
    current["singleValueExtendedProperties"] = json!([{"id":PREFERENCES_ID,"value":json!({"nativeReminderOn":true,"nativeReminderMinutes":10,"reminders":{"useDefault":false,"overrides":[{"method":"popup","minutes":10},{"method":"popup","minutes":30}]}}).to_string()}]);
    let reminders = normalize::projection(&target(), current, vec![])
        .unwrap()
        .upsert
        .event
        .reminders;
    assert_eq!(
        reminders.overrides,
        vec![EventReminderOverride {
            method: "popup".into(),
            minutes: 60
        }]
    );
}

#[test]
fn custom_zones_do_not_poison_timed_calendar_pages_and_sequence_tracks_invitation_updates() {
    let mut value = event("custom");
    value["originalStartTimeZone"] = json!("tzone://Microsoft/Custom");
    value["singleValueExtendedProperties"] = json!([{"id":APPOINTMENT_SEQUENCE_ID,"value":"3"}]);
    let projection = normalize::projection(&target(), value, vec![])
        .unwrap()
        .upsert;
    assert_eq!(projection.event.sequence, 3);
    assert!(
        matches!(projection.event.time,EventTime::Timed {time_zone:Some(ref zone),..} if zone=="Etc/UTC")
    );
}

#[test]
fn the_organizer_of_a_created_event_holds_it_while_guests_have_not_answered() {
    let mut value = event("created");
    value["organizer"] = json!({"emailAddress":{"address":"[email protected]","name":"Owner"}});
    value["attendees"] = json!([
        {
            "emailAddress":{"address":"[email protected]","name":"Owner"},
            "type":"required",
            "status":{"response":"none","time":"0001-01-01T00:00:00Z"}
        },
        {
            "emailAddress":{"address":"[email protected]","name":"Ada"},
            "type":"required",
            "status":{"response":"none","time":"0001-01-01T00:00:00Z"}
        }
    ]);

    let projection = normalize::projection(&target(), value, vec![])
        .unwrap()
        .upsert;

    assert_eq!(
        projection
            .event
            .attendees
            .iter()
            .map(|attendee| (
                attendee.email.as_str(),
                attendee.is_organizer,
                attendee.response_status
            ))
            .collect::<Vec<_>>(),
        [
            ("[email protected]", true, AttendeeResponseStatus::Accepted),
            (
                "[email protected]",
                false,
                AttendeeResponseStatus::NeedsAction
            ),
        ]
    );
}

#[test]
fn until_before_the_daily_start_excludes_that_whole_date() {
    let time = EventTime::Timed {
        starts_at: "2026-10-01T10:00:00Z".parse().unwrap(),
        ends_at: "2026-10-01T11:00:00Z".parse().unwrap(),
        time_zone: Some("UTC".into()),
    };
    for (until, date) in [
        ("20261005T090000Z", "2026-10-04"),
        ("20261005T100000Z", "2026-10-05"),
        ("20261005T110000Z", "2026-10-05"),
    ] {
        let value =
            recurrence::to_graph(&[format!("RRULE:FREQ=DAILY;UNTIL={until}")], &time).unwrap();
        assert_eq!(value["range"]["endDate"], date);
    }
}

#[test]
fn description_edits_and_clear_keep_the_provider_meeting_block() {
    let blob = "<div class=\"me-email-text\">Join <a href=\"https://teams.example/join\">meeting</a> PIN 123</div>";
    let current = json!({"isOnlineMeeting":true,"onlineMeeting":{"joinUrl":"https://teams.example/join"},"body":{"content":format!("<html><body><p>Old description</p>{blob}</body></html>")}});
    for description in ["<p>New description</p>", ""] {
        let body = patch_body(
            &CalendarEventPatch {
                description: Some(description.into()),
                ..Default::default()
            },
            Some(&current),
        )
        .unwrap();
        assert_eq!(body["body"]["content"], format!("{description}{blob}"));
    }
}

#[tokio::test]
async fn moved_event_is_absent_from_its_old_calendar_even_if_mailbox_id_survives() {
    let (server, api) = setup().await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/events/moved"))
        .respond_with(ResponseTemplate::new(200).set_body_json(event("moved")))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/events/moved"))
        .respond_with(ResponseTemplate::new(404))
        .expect(1)
        .mount(&server)
        .await;
    assert!(matches!(
        api.refresh_calendar_event("token", &target(), "moved")
            .await
            .unwrap(),
        OutlookEventRefresh::Gone
    ));
}

#[test]
fn automatic_decline_preferences_survive_reminder_edits_and_identical_retries() {
    let properties = OutOfOfficeProperties {
        auto_decline_mode: OutOfOfficeAutoDeclineMode::DeclineOnlyNewConflictingInvitations,
        decline_message: Some("I'm away".into()),
    };
    let patch = CalendarEventPatch {
        out_of_office: Some(properties.clone()),
        reminders: Some(EventReminders::default()),
        ..Default::default()
    };
    let body = patch_body(&patch, None).unwrap();
    let mut current = event("away");
    current["showAs"] = body["showAs"].clone();
    current["singleValueExtendedProperties"] = body["singleValueExtendedProperties"].clone();
    let policy = normalize::projection(&target(), current.clone(), vec![])
        .unwrap()
        .upsert
        .source
        .details()
        .automatic_decline
        .clone()
        .unwrap();
    assert_eq!(policy.properties, properties);
    let retried = patch_body(&patch, Some(&current)).unwrap();
    assert_eq!(
        retried["singleValueExtendedProperties"],
        body["singleValueExtendedProperties"]
    );
    let edited_reply = patch_body(
        &CalendarEventPatch {
            out_of_office: Some(OutOfOfficeProperties {
                auto_decline_mode: properties.auto_decline_mode,
                decline_message: Some("Updated away reply".into()),
            }),
            ..Default::default()
        },
        Some(&current),
    )
    .unwrap();
    let mut updated = current.clone();
    updated["singleValueExtendedProperties"] =
        edited_reply["singleValueExtendedProperties"].clone();
    let edited_policy = normalize::projection(&target(), updated, vec![])
        .unwrap()
        .upsert
        .source
        .details()
        .automatic_decline
        .clone()
        .unwrap();
    assert_eq!(edited_policy.enabled_at, policy.enabled_at);
    assert_eq!(edited_policy.id, policy.id);

    let changed_reminder = patch_body(
        &CalendarEventPatch {
            reminders: Some(EventReminders {
                use_default: false,
                overrides: vec![],
            }),
            ..Default::default()
        },
        Some(&current),
    )
    .unwrap();
    current["singleValueExtendedProperties"] =
        changed_reminder["singleValueExtendedProperties"].clone();
    assert_eq!(
        normalize::projection(&target(), current.clone(), vec![])
            .unwrap()
            .upsert
            .source
            .details()
            .automatic_decline
            .as_ref(),
        Some(&policy)
    );
    current["showAs"] = json!("busy");
    assert!(
        normalize::projection(&target(), current.clone(), vec![])
            .unwrap()
            .upsert
            .source
            .details()
            .automatic_decline
            .is_none()
    );
    let enabled_again = patch_body(&patch, Some(&current)).unwrap();
    current["showAs"] = enabled_again["showAs"].clone();
    current["singleValueExtendedProperties"] =
        enabled_again["singleValueExtendedProperties"].clone();
    let new_policy = normalize::projection(&target(), current, vec![])
        .unwrap()
        .upsert
        .source
        .details()
        .automatic_decline
        .clone()
        .unwrap();
    assert_ne!(new_policy.id, policy.id);
    assert!(new_policy.enabled_at >= policy.enabled_at);
}

#[tokio::test]
async fn automatic_decline_sends_the_custom_reply_once_without_replaying_a_server_failure() {
    use calendar_events::domain::outlook::automatic_decline::AutomaticDeclineProvider;
    let (server, api) = setup().await;
    Mock::given(method("POST"))
        .and(path(
            "/v1.0/me/calendars/calendar/events/invitation/decline",
        ))
        .and(body_partial_json(
            json!({"sendResponse":true,"comment":"Away until Monday"}),
        ))
        .respond_with(ResponseTemplate::new(503))
        .expect(1)
        .mount(&server)
        .await;
    assert!(
        api.decline_away_invitation("token", &target(), "invitation", Some("Away until Monday"))
            .await
            .is_err()
    );
}

#[test]
fn ordinary_outlook_recurrence_round_trips_in_the_shared_editor_shape() {
    for (pattern, expected) in [
        (
            json!({"type":"absoluteMonthly","interval":1,"dayOfMonth":2}),
            "RRULE:FREQ=MONTHLY;INTERVAL=1",
        ),
        (
            json!({"type":"absoluteYearly","interval":1,"dayOfMonth":2,"month":11}),
            "RRULE:FREQ=YEARLY;INTERVAL=1",
        ),
        (
            json!({"type":"relativeMonthly","interval":1,"daysOfWeek":["monday"],"index":"first"}),
            "RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=1MO",
        ),
    ] {
        let mut current = event("series");
        current["recurrence"] = json!({"pattern":pattern,"range":{"type":"noEnd","startDate":"2026-11-02","recurrenceTimeZone":"America/Los_Angeles"}});
        let lines = recurrence::from_graph(&current).unwrap();
        assert_eq!(lines, vec![expected.to_owned()]);
        let body = recurrence::to_graph(&lines, &normalize::event_time(&current).unwrap()).unwrap();
        assert_eq!(body["pattern"], current["recurrence"]["pattern"]);
    }
}

/// A weekly meeting another calendar system organized, as Exchange imported it
/// from the invitation, after the organizer ended the series ("this and
/// following"): Graph names the range's zone with its own alias for UTC.
pub(super) fn ended_imported_series(id: &str) -> Value {
    json!({
        "id":id,"@odata.etag":"W/\"4\"","iCalUId":format!("040000008200E00074C5B7101A82E008{id}"),
        "type":"seriesMaster","subject":"Team sync","isCancelled":false,"isAllDay":false,
        "createdDateTime":"2026-11-02T18:08:30Z","lastModifiedDateTime":"2026-11-02T19:10:12Z",
        "originalStartTimeZone":"tzone://Microsoft/Custom","originalEndTimeZone":"tzone://Microsoft/Custom",
        "start":{"dateTime":"2026-10-21T11:00:00.0000000","timeZone":"UTC"},
        "end":{"dateTime":"2026-10-21T11:30:00.0000000","timeZone":"UTC"},
        "organizer":{"emailAddress":{"address":"[email protected]","name":"Organizer"}},
        "attendees":[],
        "recurrence":{
            "pattern":{"type":"weekly","interval":1,"month":0,"dayOfMonth":0,"daysOfWeek":["wednesday"],"firstDayOfWeek":"monday","index":"first"},
            "range":{"type":"endDate","startDate":"2026-10-21","endDate":"2026-11-03","recurrenceTimeZone":"tzone://Microsoft/Utc","numberOfOccurrences":0}
        }
    })
}

#[test]
fn an_imported_series_ended_by_its_organizer_reads_graphs_utc_alias() {
    let series = ended_imported_series("series");
    assert_eq!(
        recurrence::from_graph(&series).unwrap(),
        vec!["RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=WE;WKST=MO;UNTIL=20261103T235959Z".to_owned()]
    );
    let instances = ["2026-10-21", "2026-10-28"].map(|day| {
        let mut instance = series.clone();
        instance["id"] = json!(format!("series-{day}"));
        instance["type"] = json!("occurrence");
        instance["seriesMasterId"] = json!("series");
        instance["originalStart"] = json!(format!("{day}T11:00:00Z"));
        instance["start"]["dateTime"] = json!(format!("{day}T11:00:00.0000000"));
        instance["end"]["dateTime"] = json!(format!("{day}T11:30:00.0000000"));
        instance
    });
    let upsert = normalize::projection(&target(), series, instances.to_vec())
        .unwrap()
        .upsert;
    assert_eq!(upsert.occurrences.len(), 2);
}

#[test]
fn an_end_date_in_a_zone_macro_cannot_resolve_is_read_in_the_events_own_zone() {
    let mut series = ended_imported_series("series");
    series["originalStartTimeZone"] = json!("Pacific Standard Time");
    series["recurrence"]["range"]["recurrenceTimeZone"] = json!("tzone://Microsoft/Custom");
    let lines = recurrence::from_graph(&series).unwrap();
    assert_eq!(
        lines,
        vec!["RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=WE;WKST=MO;UNTIL=20261104T075959Z".to_owned()],
        "the end of November 3 in Los Angeles"
    );
    let body = recurrence::to_graph(&lines, &normalize::event_time(&series).unwrap()).unwrap();
    assert_eq!(body["range"]["endDate"], "2026-11-03");
}

#[tokio::test]
async fn an_event_macro_cannot_read_names_the_rejected_field() {
    let (server, api) = setup().await;
    let mut hourly = event("hourly");
    hourly["type"] = json!("seriesMaster");
    hourly["recurrence"] = json!({"pattern":{"type":"hourly","interval":1},"range":{"type":"noEnd","startDate":"2026-11-02"}});
    let mut series = event("series");
    series["type"] = json!("seriesMaster");
    series["recurrence"] = json!({"pattern":{"type":"daily","interval":1},"range":{"type":"noEnd","startDate":"2026-11-02"}});
    let mut occurrence = event("occurrence");
    occurrence["start"]["dateTime"] = json!("next Monday");
    for (master, instances, field) in [
        (hourly, vec![], "recurrence.pattern.type"),
        (series, vec![occurrence], "instances.start.dateTime"),
    ] {
        let id = master["id"].as_str().unwrap().to_owned();
        Mock::given(method("GET"))
            .and(path(format!("/v1.0/me/calendars/calendar/events/{id}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(master))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("/v1.0/me/events/{id}/instances")))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"value":instances})))
            .mount(&server)
            .await;
        match api.refresh_calendar_event("token", &target(), &id).await {
            Ok(OutlookEventRefresh::Unreadable { field: rejected }) => assert_eq!(rejected, field),
            _ => panic!("{id} should be unreadable at {field}"),
        }
    }
}

/// A daily meeting Graph holds at 10:00 in Los Angeles on each of the next
/// three days, as `instances` lists it, organized by `organizer`. Its third
/// meeting moved to 11:00 with a title of its own.
pub(super) fn upcoming_series(
    id: &str,
    organizer: &str,
    is_organizer: bool,
) -> (Value, Vec<Value>) {
    let days: Vec<_> = (1..=3)
        .map(|n| Utc::now().date_naive() + chrono::Days::new(n))
        .collect();
    let at = |day: chrono::NaiveDate, hour: u32| {
        day.and_hms_opt(hour, 0, 0)
            .unwrap()
            .and_local_timezone(chrono_tz::America::Los_Angeles)
            .unwrap()
            .to_utc()
    };
    let graph_time = |instant: chrono::DateTime<Utc>| json!({"dateTime":instant.format("%Y-%m-%dT%H:%M:%S.0000000").to_string(),"timeZone":"UTC"});
    let instance = |instance_id: String, kind: &str, day: chrono::NaiveDate, hour: u32| {
        let mut value = documented_instance(&instance_id, kind, "2019-04-08", "2019-04-08");
        value["subject"] = json!("Daily standup");
        value["iCalUId"] = json!(format!("{id}-uid"));
        value["seriesMasterId"] = json!(id);
        value["isOrganizer"] = json!(is_organizer);
        value["organizer"] = json!({"emailAddress":{"name":"Organizer","address":organizer}});
        value["start"] = graph_time(at(day, hour));
        value["end"] = graph_time(at(day, hour) + chrono::Duration::minutes(30));
        value["originalStart"] =
            json!(at(day, 10).to_rfc3339_opts(chrono::SecondsFormat::Secs, true));
        value
    };
    let mut master = instance(id.into(), "seriesMaster", days[0], 10);
    for property in ["originalStart", "seriesMasterId"] {
        master.as_object_mut().unwrap().remove(property);
    }
    master["recurrence"] = json!({
        "pattern":{"type":"daily","interval":1,"month":0,"dayOfMonth":0,"firstDayOfWeek":"sunday","index":"first"},
        "range":{"type":"numbered","startDate":days[0].to_string(),"endDate":"0001-01-01","recurrenceTimeZone":"Pacific Standard Time","numberOfOccurrences":3}
    });
    let mut instances: Vec<_> = days[..2]
        .iter()
        .map(|day| instance(format!("{id}-{day}"), "occurrence", *day, 10))
        .collect();
    let mut moved = instance(format!("{id}-{}", days[2]), "exception", days[2], 11);
    moved["subject"] = json!("Daily standup, an hour later");
    instances.push(moved);
    (master, instances)
}

fn without_ids(mut upsert: CalendarEventUpsert) -> CalendarEventUpsert {
    upsert.event.id = Uuid::nil();
    for occurrence in &mut upsert.occurrences {
        occurrence.event_id = Uuid::nil();
    }
    upsert
}

async fn serve_series(server: &MockServer, master: &Value, instances: Vec<Value>) {
    let id = master["id"].as_str().unwrap();
    Mock::given(method("GET"))
        .and(path(format!("/v1.0/me/calendars/calendar/events/{id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(master))
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path(format!("/v1.0/me/events/{id}/instances")))
        .respond_with(Instances(instances))
        .mount(server)
        .await;
}

#[test]
fn instances_select_every_default_event_property_and_the_original_start() {
    let instance = documented_instance("instance", "occurrence", "2019-04-08", "2019-04-08");
    let documented: std::collections::BTreeSet<_> = instance
        .as_object()
        .unwrap()
        .keys()
        .filter(|key| !key.starts_with("@odata."))
        .map(String::as_str)
        .collect();
    let selected: std::collections::BTreeSet<_> = INSTANCE_PROPERTIES.iter().copied().collect();
    assert_eq!(
        selected, documented,
        "instances select what Graph returns by default, plus originalStart, and nothing it does not document"
    );
}

#[tokio::test]
async fn a_series_reads_the_same_through_its_selected_instances_as_from_complete_ones() {
    let (server, api) = setup().await;
    let (master, instances) = documented_series();
    serve_series(&server, &master, instances.clone()).await;
    let target = april_2019();
    let Ok(OutlookEventRefresh::Refreshed { upsert, skipped }) = api
        .refresh_calendar_event("token", &target, "AAMkAGUzYRgWAAA=")
        .await
    else {
        panic!("the documented series should be readable");
    };
    assert!(skipped.is_empty());
    let complete = normalize::projection(&target, master, instances)
        .unwrap()
        .upsert;
    assert_eq!(
        without_ids(*upsert.clone()),
        without_ids(complete),
        "no property the normalizer reads is missing from the selection"
    );
    let moved = &upsert.overrides[0];
    assert_eq!(moved.recurrence_id, "2019-04-15T20:30:00+00:00");
    assert_eq!(
        moved.title.as_deref(),
        Some("Review strategy for Q3 (moved)")
    );
    assert_eq!(moved.location.as_deref(), Some("Board room"));
    assert!(
        upsert
            .occurrences
            .iter()
            .all(|occurrence| occurrence.recurrence_id.as_ref() == Some(&occurrence.occurrence_key)),
        "every occurrence is addressed by its original start"
    );
}

#[test]
fn an_exception_without_its_original_start_is_left_out_of_an_imported_series() {
    let (master, mut instances) = documented_series();
    // Graph's documented response, which selects no originalStart.
    instances[0]
        .as_object_mut()
        .unwrap()
        .remove("originalStart");
    let projection = normalize::projection(&april_2019(), master, instances).unwrap();
    assert_eq!(
        projection.skipped,
        vec![SkippedOccurrence {
            provider_id: "AAMkAGUzYAgI1sE1TatAAEYAAAAAlNFb2CNPe0ucP9you".into(),
            field: "instances.originalStart.missing".into(),
        }]
    );
    assert!(projection.upsert.overrides.is_empty());
    let days: Vec<_> = projection
        .upsert
        .occurrences
        .iter()
        .map(|occurrence| occurrence.occurrence_key.as_str())
        .collect();
    assert_eq!(
        days,
        [
            "2019-04-08T20:30:00+00:00",
            "2019-04-22T20:30:00+00:00",
            "2019-04-29T20:30:00+00:00"
        ],
        "the rest of the series is imported"
    );
}

#[test]
fn an_original_start_macro_cannot_parse_rejects_the_series_at_its_own_field() {
    let (master, mut instances) = documented_series();
    instances[0]["originalStart"] = json!("2019-04-15");
    assert_eq!(
        normalize::projection(&april_2019(), master, instances).err(),
        Some(Rejected::at("instances.originalStart"))
    );
}

#[test]
fn occurrence_preferences_override_or_inherit_series_reminders_and_decline_policy() {
    let policy = AutomaticDeclinePolicy {
        id: Uuid::now_v7(),
        enabled_at: Utc::now(),
        properties: OutOfOfficeProperties {
            auto_decline_mode: OutOfOfficeAutoDeclineMode::DeclineAllConflictingInvitations,
            decline_message: None,
        },
    };
    let mut master = event("series");
    master["showAs"] = json!("oof");
    master["isReminderOn"] = json!(false);
    master["singleValueExtendedProperties"] = json!([{"id":PREFERENCES_ID,"value":json!({
        "nativeReminderOn":false,"reminders":{"useDefault":false,"overrides":[{"method":"email","minutes":30}]},"automaticDecline":policy,
    }).to_string()}]);
    let mut instance = master.clone();
    instance["id"] = json!("exception");
    instance["type"] = json!("exception");
    instance["originalStart"] = json!("2026-11-02T17:00:00Z");
    instance["singleValueExtendedProperties"] = json!([]);
    let inherited = normalize::projection(&target(), master.clone(), vec![instance.clone()])
        .unwrap()
        .upsert;
    assert_eq!(
        inherited.overrides[0].reminders.as_ref().unwrap(),
        &inherited.event.reminders
    );
    assert!(inherited.overrides[0].automatic_decline.is_none());
    let mut disabled = policy.clone();
    disabled.properties.auto_decline_mode = OutOfOfficeAutoDeclineMode::DeclineNone;
    instance["singleValueExtendedProperties"] = json!([{"id":PREFERENCES_ID,"value":json!({
        "nativeReminderOn":false,"reminders":{"useDefault":false,"overrides":[]},"automaticDecline":disabled,
    }).to_string()}]);
    let overridden = normalize::projection(&target(), master, vec![instance])
        .unwrap()
        .upsert;
    assert!(
        overridden.overrides[0]
            .reminders
            .as_ref()
            .unwrap()
            .overrides
            .is_empty()
    );
    assert_eq!(
        overridden.overrides[0].automatic_decline.as_ref(),
        Some(&disabled)
    );
    assert_eq!(
        overridden.source.details().automatic_decline.as_ref(),
        Some(&policy)
    );
}

fn guest(email: &str) -> CalendarAttendeeInput {
    CalendarAttendeeInput {
        email: email.into(),
        is_optional: false,
        response_status: None,
    }
}

/// A meeting with Ada, who accepted, on the mailbox's calendar.
fn meeting(id: &str, is_organizer: bool) -> Value {
    let mut meeting = event(id);
    meeting["isOrganizer"] = json!(is_organizer);
    meeting["organizer"] = json!({"emailAddress":{"address":"[email protected]","name":"Olivia"}});
    meeting["attendees"] = json!([{
        "emailAddress":{"address":"[email protected]","name":"Ada"},
        "type":"required",
        "status":{"response":"accepted","time":"2026-10-20T10:00:00Z"}
    }]);
    meeting
}

#[tokio::test]
async fn an_organizer_adds_guests_by_writing_the_whole_attendee_list() {
    let (server, api) = setup().await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/events/event"))
        .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", true)))
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .and(path("/v1.0/me/events/event"))
        .and(header("if-match", "W/\"1\""))
        .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", true)))
        .expect(1)
        .mount(&server)
        .await;

    let outcome = api
        .add_calendar_guests(
            &AccessToken::new("token".to_owned()),
            &target(),
            "event",
            &[
                guest("[email protected]"),
                guest("[email protected]"),
                guest("[email protected]"),
            ],
            &CalendarUpdateScope::All,
        )
        .await
        .unwrap();

    assert!(matches!(outcome, ProviderInviteOutcome::Applied(_)));
    let requests = server.received_requests().await.unwrap();
    let patch = requests
        .iter()
        .find(|r| r.method.as_str() == "PATCH")
        .unwrap();
    assert_eq!(
        serde_json::from_slice::<Value>(&patch.body).unwrap(),
        json!({"attendees":[
            {
                "emailAddress":{"address":"[email protected]","name":"Ada"},
                "type":"required",
                "status":{"response":"accepted","time":"2026-10-20T10:00:00Z"}
            },
            {"emailAddress":{"address":"[email protected]"},"type":"required"}
        ]}),
        "Ada keeps her answer, and only Bo is new"
    );
}

#[tokio::test]
async fn an_attendee_cannot_add_guests_to_an_outlook_meeting() {
    let (server, api) = setup().await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/events/event"))
        .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", false)))
        .mount(&server)
        .await;

    let result = api
        .add_calendar_guests(
            &AccessToken::new("token".to_owned()),
            &target(),
            "event",
            &[guest("[email protected]")],
            &CalendarUpdateScope::All,
        )
        .await;

    assert!(
        matches!(&result, Err(error) if error.kind() == CalendarProviderErrorKind::Permanent),
        "the refusal stays a typed provider error"
    );
    assert!(
        server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .all(|r| r.method.as_str() == "GET")
    );
}

#[tokio::test]
async fn guests_already_on_the_meeting_write_nothing() {
    let (server, api) = setup().await;
    Mock::given(method("GET"))
        .and(path("/v1.0/me/calendars/calendar/events/event"))
        .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", true)))
        .mount(&server)
        .await;

    let outcome = api
        .add_calendar_guests(
            &AccessToken::new("token".to_owned()),
            &target(),
            "event",
            &[guest("[email protected]")],
            &CalendarUpdateScope::All,
        )
        .await
        .unwrap();

    assert!(matches!(outcome, ProviderInviteOutcome::Applied(_)));
    assert!(
        server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .all(|r| r.method.as_str() == "GET")
    );
}