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.

63.5 KB
Raw Blame
mod add_shared_calendar_event;
mod copies;
mod read_calendar_event;

use std::sync::Mutex;

use ai_toolset::schema::generate_validated_input_schema;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolSet};
use chrono::{NaiveDate, TimeZone, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;

use super::*;
use crate::domain::meeting_links::{MeetingLink, MeetingLinkError, MeetingLinkRequest};
use crate::domain::models::{
    AttendeeResponseStatus, CalendarAttendee, CalendarEventDraft, CalendarEventPatch,
    CalendarOccurrence, CalendarSyncStatus, ConferenceChange, EventReminderOverride,
    EventReminders, EventStatus, EventTransparency, EventType, EventVisibility, GuestPolicy,
    MeetingCopy, OccurrenceRange, ViewerCapabilities, VisibleCalendar,
};
use crate::domain::ports::{
    CalendarDeletionScope, CalendarMutationError, CalendarMutationService,
    CalendarOccurrenceService, CalendarRsvpScope, CalendarUpdateScope, MeetingLinkProvider,
};

#[test]
fn tool_input_schemas_satisfy_strict_mode() {
    for (name, result) in [
        (
            "ListCalendarEvents",
            generate_validated_input_schema::<ListCalendarEvents>().map(|schema| schema.name),
        ),
        (
            "ListCalendars",
            generate_validated_input_schema::<ListCalendars>().map(|schema| schema.name),
        ),
        (
            "ReadCalendarEvent",
            generate_validated_input_schema::<ReadCalendarEvent>().map(|schema| schema.name),
        ),
        (
            "CreateCalendarEvent",
            generate_validated_input_schema::<CreateCalendarEvent>().map(|schema| schema.name),
        ),
        (
            "CreateConfirmedCalendarEvent",
            generate_validated_input_schema::<CreateConfirmedCalendarEvent>()
                .map(|schema| schema.name),
        ),
        (
            "UpdateCalendarEvent",
            generate_validated_input_schema::<UpdateCalendarEvent>().map(|schema| schema.name),
        ),
        (
            "DeleteCalendarEvent",
            generate_validated_input_schema::<DeleteCalendarEvent>().map(|schema| schema.name),
        ),
        (
            "AddSharedCalendarEvent",
            generate_validated_input_schema::<AddSharedCalendarEvent>().map(|schema| schema.name),
        ),
    ] {
        match result {
            Ok(schema_name) => assert_eq!(schema_name, name, "schema title for {name}"),
            Err(error) => panic!("schema for {name} failed validation: {error:?}"),
        }
    }
}

#[test]
fn event_time_input_deserializes_both_shapes() {
    let timed: EventTimeInput = serde_json::from_value(serde_json::json!({
        "kind": "timed",
        "startsAt": "2026-08-20T17:00:00Z",
        "endsAt": "2026-08-20T18:00:00Z",
        "timeZone": "America/New_York",
    }))
    .unwrap();
    assert!(matches!(timed, EventTimeInput::Timed { .. }));

    let all_day: EventTimeInput = serde_json::from_value(serde_json::json!({
        "kind": "allDay",
        "startDate": "2026-08-20",
        "endDate": "2026-08-21",
    }))
    .unwrap();
    assert!(matches!(all_day, EventTimeInput::AllDay { .. }));
}

fn sample_event(recurrence_lines: Vec<String>) -> crate::domain::models::CalendarEvent {
    crate::domain::models::CalendarEvent {
        id: Uuid::from_u128(7),
        owner_id: "macro|[email protected]".to_string(),
        ical_uid: "uid-1".to_string(),
        calendar_id: Some(Uuid::from_u128(9)),
        sources: Vec::new(),
        title: "Standup".to_string(),
        description: Some("Daily sync".to_string()),
        location: Some("Room 1".to_string()),
        status: EventStatus::Confirmed,
        visibility: EventVisibility::Default,
        transparency: EventTransparency::Opaque,
        event_type: EventType::Default,
        time: EventTime::Timed {
            starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),
            time_zone: Some("America/New_York".to_string()),
        },
        recurrence_lines,
        organizer_email: Some("[email protected]".to_string()),
        organizer_name: None,
        creator_email: None,
        creator_name: None,
        conference_url: Some("https://meet.google.com/abc".to_string()),
        conference_provider: Some(crate::domain::models::ConferenceProvider::GoogleMeet),
        sequence: 0,
        is_read_only: false,
        attendees: vec![
            CalendarAttendee {
                email: "[email protected]".to_string(),
                display_name: None,
                response_status: AttendeeResponseStatus::Accepted,
                is_organizer: true,
                is_optional: false,
                is_self: true,
                comment: None,
            },
            CalendarAttendee {
                email: "[email protected]".to_string(),
                display_name: None,
                response_status: AttendeeResponseStatus::NeedsAction,
                is_organizer: false,
                is_optional: true,
                is_self: false,
                comment: None,
            },
        ],
        reminders: EventReminders::default(),
        guest_policy: GuestPolicy::default(),
        is_snapshot: false,
        viewer_can: ViewerCapabilities::NONE,
        created_at: Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),
        updated_at: Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),
    }
}

fn occurrence_of(
    event: &crate::domain::models::CalendarEvent,
    key: &str,
    is_cancelled: bool,
) -> CalendarOccurrence {
    CalendarOccurrence {
        event_id: event.id,
        occurrence_key: key.to_string(),
        recurrence_id: None,
        time: event.time.clone(),
        is_cancelled,
    }
}

type RecordedCreate = (Option<Uuid>, Option<Uuid>, CalendarEventDraft);

#[derive(Default)]
struct MockMutations {
    created: Mutex<Vec<RecordedCreate>>,
    create_error: Mutex<Option<CalendarMutationError>>,
    updated: Mutex<Vec<(Uuid, CalendarEventPatch, CalendarUpdateScope)>>,
    deleted: Mutex<Vec<(Uuid, CalendarDeletionScope)>>,
    answered: Mutex<Vec<(Uuid, AttendeeResponseStatus, CalendarRsvpScope)>>,
    calendars: Mutex<Vec<VisibleCalendar>>,
    copied: Mutex<Vec<(Uuid, Option<Uuid>)>>,
    copy_error: Mutex<Option<CalendarMutationError>>,
}

impl CalendarMutationService for MockMutations {
    async fn create_event(
        &self,
        _requester_id: &str,
        email_link_id: Option<Uuid>,
        calendar_id: Option<Uuid>,
        draft: CalendarEventDraft,
    ) -> Result<crate::domain::models::CalendarEvent, CalendarMutationError> {
        if let Some(error) = self.create_error.lock().unwrap().take() {
            return Err(error);
        }
        self.created
            .lock()
            .unwrap()
            .push((email_link_id, calendar_id, draft));
        Ok(sample_event(Vec::new()))
    }

    async fn list_visible_calendars(
        &self,
        _requester_id: &str,
    ) -> Result<Vec<VisibleCalendar>, CalendarMutationError> {
        Ok(self.calendars.lock().unwrap().clone())
    }

    async fn update_event(
        &self,
        _requester_id: &str,
        event_id: Uuid,
        _calendar_id: Option<Uuid>,
        patch: CalendarEventPatch,
        scope: CalendarUpdateScope,
    ) -> Result<crate::domain::models::CalendarEvent, CalendarMutationError> {
        self.updated.lock().unwrap().push((event_id, patch, scope));
        Ok(sample_event(Vec::new()))
    }

    async fn delete_event(
        &self,
        _requester_id: &str,
        event_id: Uuid,
        _calendar_id: Option<Uuid>,
        scope: CalendarDeletionScope,
    ) -> Result<(), CalendarMutationError> {
        self.deleted.lock().unwrap().push((event_id, scope));
        Ok(())
    }

    async fn respond_to_event(
        &self,
        _requester_id: &str,
        event_id: Uuid,
        _calendar_id: Option<Uuid>,
        response: AttendeeResponseStatus,
        scope: CalendarRsvpScope,
        _responding_email: Option<String>,
    ) -> Result<crate::domain::models::CalendarEvent, CalendarMutationError> {
        self.answered
            .lock()
            .unwrap()
            .push((event_id, response, scope));
        Ok(sample_event(Vec::new()))
    }

    async fn invite_guests(
        &self,
        _requester_id: &str,
        _event_id: Uuid,
        _calendar_id: Option<Uuid>,
        _guests: Vec<CalendarAttendeeInput>,
        _scope: CalendarUpdateScope,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        unreachable!("the toolset adds guests through update_event")
    }

    async fn copy_shared_event(
        &self,
        _requester_id: &str,
        event_id: Uuid,
        calendar_id: Option<Uuid>,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        if let Some(error) = self.copy_error.lock().unwrap().take() {
            return Err(error);
        }
        self.copied.lock().unwrap().push((event_id, calendar_id));
        Ok(sample_event(Vec::new()))
    }

    async fn respond_to_join_request(
        &self,
        _requester_id: &str,
        _request_id: Uuid,
        _accept: bool,
    ) -> Result<crate::domain::join_requests::CalendarJoinRequest, CalendarMutationError> {
        unreachable!("no calendar tool answers join requests")
    }

    async fn disconnect_calendar(
        &self,
        _requester_id: &str,
        _email_link_id: Uuid,
    ) -> Result<(), CalendarMutationError> {
        unreachable!("no calendar tool disconnects calendars")
    }
}

struct MockOccurrences {
    rows: Mutex<Vec<(crate::domain::models::CalendarEvent, CalendarOccurrence)>>,
    status: CalendarSyncStatus,
    copies: Mutex<Vec<MeetingCopy>>,
}

impl CalendarOccurrenceService for MockOccurrences {
    async fn list_occurrences(
        &self,
        _requester_id: &str,
        _range: OccurrenceRange,
        cursor: Option<crate::domain::models::CalendarOccurrenceCursor>,
        limit: u16,
    ) -> Result<Vec<crate::domain::models::OccurrenceListing>, rootcause::Report> {
        let rows = self.rows.lock().unwrap().clone();
        let start = cursor
            .map(|cursor| {
                rows.iter()
                    .position(|(_, occurrence)| occurrence.occurrence_key == cursor.occurrence_key)
                    .map_or(rows.len(), |position| position + 1)
            })
            .unwrap_or(0);
        let mut page: Vec<_> = rows
            .into_iter()
            .skip(start)
            .map(
                |(event, occurrence)| crate::domain::models::OccurrenceListing {
                    event,
                    occurrence,
                    link_id: uuid::Uuid::nil(),
                    exception: Default::default(),
                },
            )
            .collect();
        page.truncate(usize::from(limit));
        Ok(page)
    }

    async fn sync_status(
        &self,
        _requester_id: &str,
    ) -> Result<CalendarSyncStatus, rootcause::Report> {
        Ok(self.status)
    }

    async fn list_visible_calendars(
        &self,
        _requester_id: &str,
    ) -> Result<Vec<crate::domain::models::VisibleCalendar>, rootcause::Report> {
        unreachable!("calendar tools list calendars through the mutation service")
    }

    async fn mention_previews(
        &self,
        _requester_id: &str,
        _items: Vec<crate::domain::models::CalendarMentionRequestItem>,
    ) -> Result<Vec<crate::domain::models::CalendarMentionPreview>, rootcause::Report> {
        unreachable!("these tests read no mentioned events")
    }

    async fn list_team_out_of_office(
        &self,
        _requester_id: &str,
        _range: OccurrenceRange,
        _limit: u16,
    ) -> Result<Vec<crate::domain::models::TeamOutOfOffice>, rootcause::Report> {
        unreachable!("no calendar tool lists team out-of-office")
    }

    async fn primary_time_zone(
        &self,
        _requester_id: &str,
    ) -> Result<Option<String>, rootcause::Report> {
        unreachable!("no calendar tool resolves the primary time zone")
    }

    async fn meeting_copies(
        &self,
        _requester_id: &str,
        _event_id: Uuid,
    ) -> Result<Vec<MeetingCopy>, rootcause::Report> {
        Ok(self.copies.lock().unwrap().clone())
    }

    async fn event_ics(
        &self,
        _requester_id: &str,
        _event_id: Uuid,
    ) -> Result<Option<crate::domain::ics::CalendarEventIcs>, rootcause::Report> {
        unreachable!("no calendar tool exports an event")
    }
}

const MEETING_URL: &str = "https://macro.com/app/meet/join/0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

#[derive(Default)]
struct MockMeetingLinks {
    requests: Mutex<Vec<MeetingLinkRequest>>,
    cancelled: Mutex<Vec<Uuid>>,
    create_error: Mutex<Option<MeetingLinkError>>,
}

impl MeetingLinkProvider for MockMeetingLinks {
    async fn create_meeting_link(
        &self,
        _requester_id: &str,
        request: MeetingLinkRequest,
    ) -> Result<MeetingLink, MeetingLinkError> {
        if let Some(error) = self.create_error.lock().unwrap().take() {
            return Err(error);
        }
        self.requests.lock().unwrap().push(request);
        Ok(MeetingLink {
            id: Uuid::from_u128(42),
            url: MEETING_URL.to_string(),
        })
    }

    async fn cancel_meeting_link(
        &self,
        _requester_id: &str,
        meeting_id: Uuid,
    ) -> Result<(), MeetingLinkError> {
        self.cancelled.lock().unwrap().push(meeting_id);
        Ok(())
    }
}

type MockContext = CalendarToolContext<MockMutations, MockOccurrences, MockMeetingLinks>;

fn context(
    mutations: MockMutations,
    occurrences: MockOccurrences,
) -> (std::sync::Arc<MockMutations>, ServiceContext<MockContext>) {
    let (mutations, _, context) =
        context_with_meeting_links(mutations, occurrences, MockMeetingLinks::default());
    (mutations, context)
}

fn context_with_meeting_links(
    mutations: MockMutations,
    occurrences: MockOccurrences,
    meeting_links: MockMeetingLinks,
) -> (
    std::sync::Arc<MockMutations>,
    std::sync::Arc<MockMeetingLinks>,
    ServiceContext<MockContext>,
) {
    let mutations = std::sync::Arc::new(mutations);
    let meeting_links = std::sync::Arc::new(meeting_links);
    let context = CalendarToolContext::new(
        mutations.clone(),
        std::sync::Arc::new(occurrences),
        meeting_links.clone(),
    );
    (mutations, meeting_links, ServiceContext(context))
}

fn request_context() -> RequestContext {
    RequestContext::new(MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap())
}

fn empty_occurrences() -> MockOccurrences {
    MockOccurrences {
        rows: Mutex::new(Vec::new()),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    }
}

fn create_tool_args() -> serde_json::Value {
    serde_json::json!({
        "title": "Design review",
        "time": {
            "kind": "timed",
            "startsAt": "2026-08-20T17:00:00Z",
            "endsAt": "2026-08-20T18:00:00Z",
            "timeZone": "America/New_York"
        },
        "attendees": [],
        "recurrenceLines": [],
        "addConference": false
    })
}

#[tokio::test]
async fn ai_toolset_defers_create_without_mutating_calendar() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let args = create_tool_args();
    let pending = calendar_toolset()
        .try_tool_call(context.0, request_context(), "CreateCalendarEvent", &args)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(pending, serde_json::json!("PendingUserExecution"));
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn mcp_toolset_executes_create_directly() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let args = create_tool_args();
    let event = mcp_toolset()
        .try_tool_call(context.0, request_context(), "CreateCalendarEvent", &args)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(event["eventId"], Uuid::from_u128(7).to_string());
    assert_eq!(mutations.created.lock().unwrap().len(), 1);
}

/// The confirmed variant takes exactly `CreateCalendarEvent`'s fields plus
/// the confirmation, and the confirmation is required: the schema is the gate.
#[test]
fn create_confirmed_is_create_plus_a_required_confirmation() {
    let confirmed = generate_validated_input_schema::<CreateConfirmedCalendarEvent>().unwrap();
    let plain = generate_validated_input_schema::<CreateCalendarEvent>().unwrap();
    assert_eq!(confirmed.name, "CreateConfirmedCalendarEvent");
    assert!(
        confirmed.description.contains("userConfirmation"),
        "{}",
        confirmed.description
    );

    let confirmed = confirmed.schema.to_value();
    let plain = plain.schema.to_value();
    let properties = |schema: &serde_json::Value| {
        let mut names: Vec<String> = schema["properties"]
            .as_object()
            .expect("an object schema")
            .keys()
            .cloned()
            .collect();
        names.sort();
        names
    };
    let mut expected = properties(&plain);
    expected.push("userConfirmation".to_owned());
    expected.sort();
    assert_eq!(properties(&confirmed), expected);
    assert!(
        confirmed["required"]
            .as_array()
            .expect("required is an array")
            .contains(&serde_json::json!("userConfirmation")),
        "{confirmed:#}"
    );
}

/// The confirmed tool is registered beside the deferring one, executes in
/// the loop rather than deferring, and creates exactly what the plain tool
/// would have.
#[tokio::test]
async fn confirmed_create_executes_directly_in_the_user_tool_toolset() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let mut args = create_tool_args();
    args["userConfirmation"] = serde_json::json!("yes, go ahead and put it on the calendar");
    let event = calendar_toolset()
        .try_tool_call(
            context.0,
            request_context(),
            "CreateConfirmedCalendarEvent",
            &args,
        )
        .await
        .unwrap()
        .unwrap();

    assert_eq!(event["eventId"], Uuid::from_u128(7).to_string());
    let created = mutations.created.lock().unwrap();
    let (_, _, draft) = created.first().expect("one create call");
    assert_eq!(draft.title, "Design review");
}

/// Composer-less hosts already create directly through the plain tool, so
/// the confirmed variant would be a second name for the same thing there.
#[tokio::test]
async fn mcp_toolset_omits_the_confirmed_create() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let mut args = create_tool_args();
    args["userConfirmation"] = serde_json::json!("yes");
    let result = mcp_toolset()
        .try_tool_call(
            context.0,
            request_context(),
            "CreateConfirmedCalendarEvent",
            &args,
        )
        .await;

    assert!(
        matches!(result, Err(ai_toolset::ToolSetError::NotFound(_))),
        "{result:?}"
    );
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn confirmed_create_refuses_a_blank_confirmation() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let mut args = create_tool_args();
    args["userConfirmation"] = serde_json::json!("   ");
    let error = calendar_toolset()
        .try_tool_call(
            context.0,
            request_context(),
            "CreateConfirmedCalendarEvent",
            &args,
        )
        .await
        .unwrap()
        .unwrap_err();

    assert!(
        error.description.contains("userConfirmation"),
        "{}",
        error.description
    );
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn create_converts_input_into_a_domain_draft() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let calendar_id = Uuid::from_u128(3);

    let tool = CreateCalendarEvent {
        title: "Design review".to_string(),
        time: EventTimeInput::AllDay {
            start_date: NaiveDate::from_ymd_opt(2026, 8, 21).unwrap(),
            end_date: NaiveDate::from_ymd_opt(2026, 8, 22).unwrap(),
        },
        description: Some("Quarterly".to_string()),
        location: None,
        attendees: vec![AttendeeInput {
            email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
            is_optional: true,
        }],
        recurrence_lines: vec!["RRULE:FREQ=WEEKLY".to_string()],
        calendar_id: Some(calendar_id),
        reminders: Some(EventRemindersInput {
            use_default: false,
            overrides: vec![EventReminderOverrideInput {
                method: "popup".to_string(),
                minutes: 15,
            }],
        }),
        add_macro_call: false,
        add_conference: true,
        event_type: CalendarEventTypeInput::Default,
        out_of_office: None,
        guest_policy: None,
    };
    let response = tool.call(context, request_context()).await.unwrap();
    assert_eq!(response.event_id, Uuid::from_u128(7));

    let created = mutations.created.lock().unwrap();
    let (email_link_id, target_calendar, draft) = created.first().expect("one create call");
    assert_eq!(*email_link_id, None);
    assert_eq!(*target_calendar, Some(calendar_id));
    assert_eq!(draft.title, "Design review");
    assert_eq!(draft.attendees.len(), 1);
    assert!(draft.attendees[0].is_optional);
    assert_eq!(
        draft.recurrence_lines,
        vec!["RRULE:FREQ=WEEKLY".to_string()]
    );
    assert_eq!(draft.conference, Some(ConferenceChange::ProviderDefault));
    assert_eq!(
        draft.reminders,
        Some(EventReminders {
            use_default: false,
            overrides: vec![EventReminderOverride {
                method: "popup".to_string(),
                minutes: 15,
            }],
        })
    );
    assert!(matches!(draft.time, EventTime::AllDay { .. }));
}

#[tokio::test]
async fn create_maps_out_of_office_input_into_the_draft() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = CreateCalendarEvent {
        title: "Out".to_string(),
        time: EventTimeInput::Timed {
            starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 12, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),
            time_zone: None,
        },
        description: None,
        location: None,
        attendees: Vec::new(),
        recurrence_lines: Vec::new(),
        calendar_id: None,
        reminders: None,
        add_macro_call: false,
        add_conference: false,
        event_type: CalendarEventTypeInput::OutOfOffice,
        out_of_office: Some(OutOfOfficeInput {
            auto_decline_mode: Some(AutoDeclineModeInput::DeclineAll),
            decline_message: Some("Away".to_string()),
        }),
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    let created = mutations.created.lock().unwrap();
    let (_, _, draft) = created.first().expect("one create call");
    let out_of_office = draft
        .out_of_office
        .as_ref()
        .expect("out-of-office properties carried into the draft");
    assert_eq!(
        out_of_office.auto_decline_mode,
        crate::domain::models::OutOfOfficeAutoDeclineMode::DeclineAllConflictingInvitations
    );
    assert_eq!(out_of_office.decline_message.as_deref(), Some("Away"));
}

#[tokio::test]
async fn create_rejects_out_of_office_settings_on_a_default_event() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = CreateCalendarEvent {
        title: "Regular".to_string(),
        time: EventTimeInput::Timed {
            starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 12, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 13, 0, 0).unwrap(),
            time_zone: None,
        },
        description: None,
        location: None,
        attendees: Vec::new(),
        recurrence_lines: Vec::new(),
        calendar_id: None,
        reminders: None,
        add_macro_call: false,
        add_conference: false,
        event_type: CalendarEventTypeInput::Default,
        out_of_office: Some(OutOfOfficeInput::default()),
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap_err();
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn create_surfaces_missing_calendar_as_an_actionable_error() {
    let mutations = MockMutations {
        create_error: Mutex::new(Some(CalendarMutationError::NoWritableCalendar)),
        ..Default::default()
    };
    let (_, context) = context(mutations, empty_occurrences());

    let tool = CreateCalendarEvent {
        title: "Lunch".to_string(),
        time: EventTimeInput::Timed {
            starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 12, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 13, 0, 0).unwrap(),
            time_zone: None,
        },
        description: None,
        location: None,
        attendees: Vec::new(),
        recurrence_lines: Vec::new(),
        calendar_id: None,
        reminders: None,
        add_macro_call: false,
        add_conference: false,
        event_type: CalendarEventTypeInput::Default,
        out_of_office: None,
        guest_policy: None,
    };
    let error = tool.call(context, request_context()).await.unwrap_err();
    assert!(
        error.description.contains("not connected a calendar"),
        "unexpected description: {}",
        error.description
    );
}

fn macro_call_tool() -> CreateCalendarEvent {
    CreateCalendarEvent {
        title: "Design review".to_string(),
        time: EventTimeInput::Timed {
            starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),
            time_zone: Some("America/New_York".to_string()),
        },
        description: Some("<p>Agenda</p>".to_string()),
        location: None,
        attendees: vec![AttendeeInput {
            email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
            is_optional: false,
        }],
        recurrence_lines: Vec::new(),
        calendar_id: Some(Uuid::from_u128(3)),
        reminders: None,
        add_macro_call: true,
        add_conference: false,
        event_type: CalendarEventTypeInput::Default,
        out_of_office: None,
        guest_policy: None,
    }
}

#[tokio::test]
async fn create_with_a_macro_call_mints_a_meeting_and_writes_its_link_into_the_event() {
    let (mutations, meeting_links, context) = context_with_meeting_links(
        MockMutations::default(),
        empty_occurrences(),
        MockMeetingLinks::default(),
    );

    let response = macro_call_tool()
        .call(context, request_context())
        .await
        .unwrap();
    assert_eq!(response.event_id, Uuid::from_u128(7));
    assert_eq!(response.macro_call_url.as_deref(), Some(MEETING_URL));

    let requests = meeting_links.requests.lock().unwrap();
    let request = requests.first().expect("one meeting minted");
    assert_eq!(request.title, "Design review");
    assert_eq!(
        request.scheduled_start,
        Some(Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap())
    );
    assert_eq!(
        request.scheduled_end,
        Some(Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap())
    );

    let created = mutations.created.lock().unwrap();
    let (_, target_calendar, draft) = created.first().expect("one create call");
    assert_eq!(*target_calendar, Some(Uuid::from_u128(3)));
    assert_eq!(draft.location.as_deref(), Some(MEETING_URL));
    assert_eq!(
        draft.description.as_deref(),
        Some(
            format!(
                "<p>Agenda</p>\n<p>Join Macro call: <a href=\"{MEETING_URL}\">{MEETING_URL}</a></p>"
            )
            .as_str()
        )
    );
    assert_eq!(draft.conference, None);
    assert_eq!(draft.attendees.len(), 1);
    assert!(meeting_links.cancelled.lock().unwrap().is_empty());
}

#[tokio::test]
async fn mcp_toolset_accepts_add_macro_call() {
    let (mutations, meeting_links, context) = context_with_meeting_links(
        MockMutations::default(),
        empty_occurrences(),
        MockMeetingLinks::default(),
    );
    let mut args = create_tool_args();
    args["addMacroCall"] = serde_json::json!(true);

    let event = mcp_toolset()
        .try_tool_call(context.0, request_context(), "CreateCalendarEvent", &args)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(event["eventId"], Uuid::from_u128(7).to_string());
    assert_eq!(event["macroCallUrl"], MEETING_URL);
    assert_eq!(meeting_links.requests.lock().unwrap().len(), 1);
    assert_eq!(mutations.created.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn create_refuses_both_a_macro_call_and_a_google_meet() {
    let (mutations, meeting_links, context) = context_with_meeting_links(
        MockMutations::default(),
        empty_occurrences(),
        MockMeetingLinks::default(),
    );

    let error = CreateCalendarEvent {
        add_conference: true,
        ..macro_call_tool()
    }
    .call(context, request_context())
    .await
    .unwrap_err();

    assert!(
        error.description.contains("mutually exclusive"),
        "unexpected description: {}",
        error.description
    );
    assert!(meeting_links.requests.lock().unwrap().is_empty());
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn create_with_a_macro_call_rolls_the_meeting_back_when_the_calendar_write_fails() {
    let (mutations, meeting_links, context) = context_with_meeting_links(
        MockMutations {
            create_error: Mutex::new(Some(CalendarMutationError::NoWritableCalendar)),
            ..Default::default()
        },
        empty_occurrences(),
        MockMeetingLinks::default(),
    );

    let error = macro_call_tool()
        .call(context, request_context())
        .await
        .unwrap_err();

    assert!(
        error.description.contains("not connected a calendar"),
        "unexpected description: {}",
        error.description
    );
    assert_eq!(
        *meeting_links.cancelled.lock().unwrap(),
        vec![Uuid::from_u128(42)]
    );
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn create_with_a_macro_call_explains_an_unwired_host() {
    let (mutations, _, context) = context_with_meeting_links(
        MockMutations::default(),
        empty_occurrences(),
        MockMeetingLinks {
            create_error: Mutex::new(Some(MeetingLinkError::Unavailable)),
            ..Default::default()
        },
    );

    let error = macro_call_tool()
        .call(context, request_context())
        .await
        .unwrap_err();

    assert!(
        error.description.contains("addConference"),
        "unexpected description: {}",
        error.description
    );
    assert!(mutations.created.lock().unwrap().is_empty());
}

#[tokio::test]
async fn update_converts_input_into_a_domain_patch() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let event_id = Uuid::from_u128(11);

    let tool = UpdateCalendarEvent {
        event_id,
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: Some("Renamed".to_string()),
        description: Some(String::new()),
        location: None,
        time: None,
        attendees: Some(vec![AttendeeInput {
            email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
            is_optional: false,
        }]),
        recurrence_lines: None,
        conference: Some(ConferenceChangeInput::Remove),
        reminders: None,
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    let updated = mutations.updated.lock().unwrap();
    let (patched_id, patch, scope) = updated.first().expect("one update call");
    assert_eq!(*patched_id, event_id);
    assert_eq!(*scope, CalendarUpdateScope::All);
    assert_eq!(patch.title.as_deref(), Some("Renamed"));
    assert_eq!(patch.description.as_deref(), Some(""));
    assert_eq!(patch.location, None);
    assert_eq!(
        patch.attendees.as_ref().map(|attendees| attendees.len()),
        Some(1)
    );
    assert_eq!(patch.conference, Some(ConferenceChange::Removed));
    assert!(patch.out_of_office.is_none());
}

#[tokio::test]
async fn update_maps_out_of_office_settings_into_the_patch() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let event_id = Uuid::from_u128(11);

    let tool = UpdateCalendarEvent {
        event_id,
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: None,
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: None,
        out_of_office: Some(OutOfOfficeInput {
            auto_decline_mode: Some(AutoDeclineModeInput::DeclineNewOnly),
            decline_message: None,
        }),
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    let updated = mutations.updated.lock().unwrap();
    let (_, patch, _) = updated.first().expect("one update call");
    let out_of_office = patch
        .out_of_office
        .as_ref()
        .expect("out-of-office settings carried into the patch");
    assert_eq!(
        out_of_office.auto_decline_mode,
        crate::domain::models::OutOfOfficeAutoDeclineMode::DeclineOnlyNewConflictingInvitations
    );
}

#[tokio::test]
async fn update_passes_the_selected_occurrence_scope() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let event_id = Uuid::from_u128(11);

    let tool = UpdateCalendarEvent {
        event_id,
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::ThisEvent,
        recurrence_id: Some("2026-08-18T20:00:00+00:00".to_string()),
        title: None,
        description: None,
        location: None,
        time: Some(EventTimeInput::Timed {
            starts_at: Utc.with_ymd_and_hms(2026, 8, 18, 20, 0, 0).unwrap(),
            ends_at: Utc.with_ymd_and_hms(2026, 8, 18, 22, 0, 0).unwrap(),
            time_zone: None,
        }),
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    let updated = mutations.updated.lock().unwrap();
    let (_, _, scope) = updated.first().expect("one update call");
    assert_eq!(
        *scope,
        CalendarUpdateScope::ThisEvent {
            recurrence_id: "2026-08-18T20:00:00+00:00".to_string(),
        }
    );
}

#[tokio::test]
async fn scoped_update_requires_a_recurrence_id() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::ThisEvent,
        recurrence_id: None,
        title: Some("Renamed".to_string()),
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    let error = tool.call(context, request_context()).await.unwrap_err();
    assert!(error.description.contains("recurrenceId"));
    assert!(mutations.updated.lock().unwrap().is_empty());
}

/// A series-wide update carrying an occurrence key is contradictory input;
/// silently dropping the key would apply a one-occurrence intent to the
/// whole series — the exact failure scoping exists to prevent.
#[tokio::test]
async fn series_update_rejects_a_stray_recurrence_id() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: Some("2026-08-18T20:00:00+00:00".to_string()),
        title: Some("Renamed".to_string()),
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    let error = tool.call(context, request_context()).await.unwrap_err();
    assert!(error.description.contains("this_event"));
    assert!(mutations.updated.lock().unwrap().is_empty());
}

#[tokio::test]
async fn update_carries_reminders_into_the_patch() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: None,
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: Some(EventRemindersInput {
            use_default: false,
            overrides: vec![EventReminderOverrideInput {
                method: "popup".to_string(),
                minutes: 30,
            }],
        }),
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    let updated = mutations.updated.lock().unwrap();
    let (_, patch, _) = updated.first().expect("one update call");
    assert_eq!(
        patch.reminders,
        Some(EventReminders {
            use_default: false,
            overrides: vec![EventReminderOverride {
                method: "popup".to_string(),
                minutes: 30,
            }],
        })
    );
}

/// An RSVP is a separate provider call, so a call carrying only one must not
/// also send an empty patch — the domain rejects a patch that changes nothing.
#[tokio::test]
async fn rsvp_alone_answers_without_patching() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let event_id = Uuid::from_u128(11);

    let tool = UpdateCalendarEvent {
        event_id,
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: None,
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: Some(RsvpResponseInput::Declined),
        out_of_office: None,
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    assert!(mutations.updated.lock().unwrap().is_empty());
    let answered = mutations.answered.lock().unwrap();
    assert_eq!(
        *answered.first().expect("one rsvp call"),
        (
            event_id,
            AttendeeResponseStatus::Declined,
            CalendarRsvpScope::All
        )
    );
}

#[tokio::test]
async fn rsvp_follows_the_occurrence_scope_of_the_call() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::ThisEvent,
        recurrence_id: Some("2026-08-18T20:00:00+00:00".to_string()),
        title: None,
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: Some(RsvpResponseInput::Tentative),
        out_of_office: None,
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    let answered = mutations.answered.lock().unwrap();
    let (_, response, scope) = answered.first().expect("one rsvp call");
    assert_eq!(*response, AttendeeResponseStatus::Tentative);
    assert_eq!(
        *scope,
        CalendarRsvpScope::ThisEvent {
            recurrence_id: "2026-08-18T20:00:00+00:00".to_string(),
        }
    );
}

/// Replacing the attendee list rewrites every response on the event, so the
/// RSVP has to be recorded after the patch rather than before it.
#[tokio::test]
async fn update_answers_after_applying_the_patch() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: None,
        description: None,
        location: None,
        time: None,
        attendees: Some(vec![AttendeeInput {
            email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
            is_optional: false,
        }]),
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: Some(RsvpResponseInput::Accepted),
        out_of_office: None,
        guest_policy: None,
    };
    tool.call(context, request_context()).await.unwrap();

    assert_eq!(mutations.updated.lock().unwrap().len(), 1);
    assert_eq!(mutations.answered.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn update_without_a_change_or_an_rsvp_is_rejected() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: None,
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    let error = tool.call(context, request_context()).await.unwrap_err();
    assert!(error.description.contains("changes nothing"));
    assert!(mutations.updated.lock().unwrap().is_empty());
    assert!(mutations.answered.lock().unwrap().is_empty());
}

#[tokio::test]
async fn scoped_deletion_requires_a_recurrence_id() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());

    let tool = DeleteCalendarEvent {
        event_id: Uuid::from_u128(11),
        calendar_id: None,
        inbox: None,
        scope: DeletionScopeInput::ThisEvent,
        recurrence_id: None,
    };
    let error = tool.call(context, request_context()).await.unwrap_err();
    assert!(error.description.contains("recurrenceId"));
    assert!(mutations.deleted.lock().unwrap().is_empty());
}

#[tokio::test]
async fn deletion_passes_the_selected_scope() {
    let (mutations, context) = context(MockMutations::default(), empty_occurrences());
    let event_id = Uuid::from_u128(11);

    let tool = DeleteCalendarEvent {
        event_id,
        calendar_id: None,
        inbox: None,
        scope: DeletionScopeInput::ThisAndFollowing,
        recurrence_id: Some("2026-08-20T17:00:00+00:00".to_string()),
    };
    let response = tool.call(context, request_context()).await.unwrap();
    assert_eq!(response.event_id, event_id);

    let deleted = mutations.deleted.lock().unwrap();
    assert_eq!(
        deleted.first(),
        Some(&(
            event_id,
            CalendarDeletionScope::ThisAndFollowing {
                recurrence_id: "2026-08-20T17:00:00+00:00".to_string(),
            }
        ))
    );
}

#[tokio::test]
async fn list_events_maps_occurrences_and_skips_cancelled_ones() {
    let recurring = sample_event(vec!["RRULE:FREQ=DAILY".to_string()]);
    let occurrences = MockOccurrences {
        rows: Mutex::new(vec![
            (recurring.clone(), occurrence_of(&recurring, "k-1", false)),
            (recurring.clone(), occurrence_of(&recurring, "k-2", true)),
        ]),
        status: CalendarSyncStatus::Syncing,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(MockMutations::default(), occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 27, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();

    assert_eq!(response.events.len(), 1, "cancelled occurrence is skipped");
    let item = &response.events[0];
    assert_eq!(item.event_id, recurring.id);
    assert!(item.is_recurring);
    assert_eq!(item.recurrence_id.as_deref(), Some("k-1"));
    assert_eq!(item.my_response.as_deref(), Some("accepted"));
    assert_eq!(item.attendee_count, 2);
    assert!(!item.is_all_day);
    assert_eq!(response.sync_status, "syncing");
    assert!(response.summary.contains("still syncing"));
    assert!(!response.truncated);
}

#[tokio::test]
async fn list_events_reports_truncation() {
    let event = sample_event(Vec::new());
    let max = usize::from(super::list_calendar_events::OCCURRENCES_MAX);
    let rows = (0..max + 1)
        .map(|index| {
            (
                event.clone(),
                occurrence_of(&event, &format!("k-{index}"), false),
            )
        })
        .collect();
    let occurrences = MockOccurrences {
        rows: Mutex::new(rows),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(MockMutations::default(), occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 27, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();
    assert_eq!(response.events.len(), max);
    assert!(response.truncated);
    assert!(response.summary.contains("narrow the window"));
}

#[tokio::test]
async fn cancelled_occurrences_do_not_count_toward_truncation() {
    let event = sample_event(Vec::new());
    let max = usize::from(super::list_calendar_events::OCCURRENCES_MAX);
    // Exactly the cap of active occurrences plus one cancelled row in the
    // middle: the first page overflows only because of the cancelled row, so
    // the tool must page past it instead of reporting truncation.
    let mut rows: Vec<_> = (0..max)
        .map(|index| {
            (
                event.clone(),
                occurrence_of(&event, &format!("k-{index}"), false),
            )
        })
        .collect();
    rows.insert(
        max / 2,
        (event.clone(), occurrence_of(&event, "k-cancelled", true)),
    );
    let occurrences = MockOccurrences {
        rows: Mutex::new(rows),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(MockMutations::default(), occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 27, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();
    assert_eq!(response.events.len(), max);
    assert!(!response.truncated);
}

#[tokio::test]
async fn list_calendars_maps_visible_calendars() {
    let mutations = MockMutations {
        calendars: Mutex::new(vec![VisibleCalendar {
            provider: crate::domain::models::CalendarProvider::Google,
            capabilities: crate::domain::models::CalendarCapabilities::google(),
            id: Uuid::from_u128(3),
            email_link_id: Uuid::from_u128(4),
            email_address: "[email protected]".to_string(),
            name: "Work".to_string(),
            color: None,
            is_primary: true,
            is_writable: true,
            is_subscription: false,
            contributes_to_availability: true,
            sync_error: None,
            default_reminders: Vec::new(),
        }]),
        ..Default::default()
    };
    {
        let mut calendars = mutations.calendars.lock().unwrap();
        let mut outlook = calendars[0].clone();
        outlook.id = Uuid::from_u128(5);
        outlook.provider = crate::domain::models::CalendarProvider::Outlook;
        outlook.capabilities = crate::domain::models::CalendarCapabilities::outlook(true);
        calendars.push(outlook);
    }
    let (_, context) = context(mutations, empty_occurrences());

    let response = ListCalendars {}
        .call(context, request_context())
        .await
        .unwrap();
    assert_eq!(response.calendars.len(), 2);
    let calendar = &response.calendars[0];
    assert_eq!(calendar.calendar_id, Uuid::from_u128(3));
    assert_eq!(calendar.email_address, "[email protected]");
    assert!(calendar.is_primary);
    assert!(calendar.is_writable);
    assert!(calendar.contributes_to_availability);
    assert_eq!(
        calendar.provider,
        crate::domain::models::CalendarProvider::Google
    );
    assert!(calendar.capabilities.remove_conference);
    let outlook = &response.calendars[1];
    assert_eq!(
        outlook.provider,
        crate::domain::models::CalendarProvider::Outlook
    );
    assert_eq!(
        outlook.capabilities.conference_provider,
        Some(crate::domain::models::ConferenceProvider::MicrosoftTeams)
    );
    assert!(!outlook.capabilities.remove_conference);
    assert!(!outlook.capabilities.reset_rsvp);
    assert_eq!(response.summary, "Found 2 calendars.");
}

fn visible_calendar(id: u128, email_link_id: u128, inbox: &str, name: &str) -> VisibleCalendar {
    VisibleCalendar {
        provider: crate::domain::models::CalendarProvider::Google,
        capabilities: crate::domain::models::CalendarCapabilities::google(),
        id: Uuid::from_u128(id),
        email_link_id: Uuid::from_u128(email_link_id),
        email_address: inbox.to_string(),
        name: name.to_string(),
        color: None,
        is_primary: true,
        is_writable: true,
        is_subscription: false,
        contributes_to_availability: true,
        sync_error: None,
        default_reminders: Vec::new(),
    }
}

/// One meeting synced through two of the user's inboxes is two entities;
/// each entry has to say which inbox holds it and what the user is there,
/// so the agent can ask by inbox instead of by id.
#[tokio::test]
async fn list_events_names_the_inbox_and_role_of_each_copy() {
    let mut organized = sample_event(Vec::new());
    organized.viewer_can = ViewerCapabilities {
        organize: true,
        ..ViewerCapabilities::NONE
    };
    let mut invited = sample_event(Vec::new());
    invited.id = Uuid::from_u128(8);
    invited.calendar_id = Some(Uuid::from_u128(10));
    invited.attendees[0].is_self = false;
    invited.attendees.push(CalendarAttendee {
        email: "[email protected]".to_string(),
        display_name: None,
        response_status: AttendeeResponseStatus::NeedsAction,
        is_organizer: false,
        is_optional: false,
        is_self: true,
        comment: None,
    });
    invited.viewer_can = ViewerCapabilities {
        rsvp: true,
        invite_guests: true,
        ..ViewerCapabilities::NONE
    };
    let mutations = MockMutations {
        calendars: Mutex::new(vec![
            visible_calendar(9, 1, "[email protected]", "Owner"),
            visible_calendar(10, 2, "[email protected]", "Second"),
        ]),
        ..Default::default()
    };
    let occurrences = MockOccurrences {
        rows: Mutex::new(vec![
            (organized.clone(), occurrence_of(&organized, "k-1", false)),
            (invited.clone(), occurrence_of(&invited, "k-1", false)),
        ]),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(mutations, occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 21, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();

    assert_eq!(response.events.len(), 2);
    let first = &response.events[0];
    assert_eq!(first.inbox.as_deref(), Some("[email protected]"));
    assert_eq!(first.calendar_name.as_deref(), Some("Owner"));
    assert_eq!(first.my_role, Some(ToolEventRole::Organizer));
    let second = &response.events[1];
    assert_eq!(second.event_id, Uuid::from_u128(8));
    assert_eq!(second.inbox.as_deref(), Some("[email protected]"));
    assert_eq!(second.calendar_name.as_deref(), Some("Second"));
    assert_eq!(second.my_role, Some(ToolEventRole::Guest));
    assert!(
        response
            .summary
            .contains("1 meeting is on more than one of the user's inboxes"),
        "summary: {}",
        response.summary
    );
}

fn source_copy(
    calendar_id: u128,
    title: &str,
) -> crate::domain::models::CalendarEventSourceContent {
    crate::domain::models::CalendarEventSourceContent {
        calendar_id: Uuid::from_u128(calendar_id),
        title: title.to_string(),
        description: None,
        location: None,
        event_type: EventType::Default,
        visibility: EventVisibility::Default,
        transparency: EventTransparency::Opaque,
        is_read_only: false,
        reminders: EventReminders::default(),
        creator_email: None,
        creator_name: None,
    }
}

#[tokio::test]
async fn list_events_labels_each_calendar_copy_of_one_entity() {
    let mut event = sample_event(Vec::new());
    event.sources = vec![source_copy(9, "Standup"), source_copy(12, "Team standup")];
    let mutations = MockMutations {
        calendars: Mutex::new(vec![
            visible_calendar(9, 1, "[email protected]", "Owner"),
            visible_calendar(12, 1, "[email protected]", "Team"),
        ]),
        ..Default::default()
    };
    let occurrences = MockOccurrences {
        rows: Mutex::new(vec![(event.clone(), occurrence_of(&event, "k-1", false))]),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(mutations, occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 21, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();

    let copies = &response.events[0].copies;
    assert_eq!(copies.len(), 2);
    assert_eq!(copies[1].calendar_name.as_deref(), Some("Team"));
    assert_eq!(copies[1].inbox.as_deref(), Some("[email protected]"));
    assert!(
        !response
            .summary
            .contains("more than one of the user's inboxes"),
        "one entity on two calendars of one inbox is not a multi-inbox meeting"
    );
}

#[test]
fn role_follows_the_copy_inbox() {
    let labels =
        CalendarLabels::from_calendars(vec![visible_calendar(9, 1, "[email protected]", "Owner")]);
    let mut event = sample_event(Vec::new());
    assert_eq!(
        ToolEventRole::of(&event, &labels),
        Some(ToolEventRole::Organizer),
        "the inbox's own row organizes"
    );

    event.attendees[0].is_self = false;
    assert_eq!(
        ToolEventRole::of(&event, &labels),
        None,
        "neither organizer nor guest"
    );

    event.attendees[1].is_self = true;
    assert_eq!(
        ToolEventRole::of(&event, &labels),
        Some(ToolEventRole::Guest)
    );

    event.attendees.clear();
    event.viewer_can = ViewerCapabilities {
        organize: true,
        ..ViewerCapabilities::NONE
    };
    assert_eq!(
        ToolEventRole::of(&event, &labels),
        Some(ToolEventRole::Organizer),
        "an own event without guests"
    );
}

/// Writing a calendar lets the user act as its organizer, which says nothing
/// about whose calendar or event it is.
#[test]
fn role_never_claims_an_event_on_someone_elses_calendar() {
    let mut shared = visible_calendar(9, 1, "[email protected]", "[email protected]");
    shared.contributes_to_availability = false;
    let labels = CalendarLabels::from_calendars(vec![shared]);
    let writer = ViewerCapabilities {
        organize: true,
        ..ViewerCapabilities::NONE
    };

    let mut event = sample_event(Vec::new());
    event.viewer_can = writer;
    event.attendees[0].is_self = false;
    assert_eq!(
        ToolEventRole::of(&event, &labels),
        None,
        "their meeting, seen on their calendar"
    );

    event.attendees.clear();
    assert_eq!(
        ToolEventRole::of(&event, &labels),
        None,
        "their event without guests"
    );

    let own_calendar =
        CalendarLabels::from_calendars(vec![visible_calendar(9, 1, "[email protected]", "Owner")]);
    let mut invited = sample_event(Vec::new());
    invited.viewer_can = writer;
    invited.attendees[0].is_self = false;
    invited.attendees[1].is_self = true;
    assert_eq!(
        ToolEventRole::of(&invited, &own_calendar),
        Some(ToolEventRole::Guest),
        "invited by someone whose calendar the user can write"
    );
}

fn holidays_calendar(id: u128, email_link_id: u128) -> VisibleCalendar {
    VisibleCalendar {
        is_primary: false,
        is_writable: false,
        contributes_to_availability: false,
        ..visible_calendar(
            id,
            email_link_id,
            "[email protected]",
            "United States holidays",
        )
    }
}

/// Microsoft Graph names the mailbox owner as organizer on every event of a
/// read-only calendar such as Outlook's holidays, so that row proves nothing
/// there. It is not a guest's row either, whatever availability says.
#[test]
fn role_ignores_an_organizer_row_on_a_read_only_calendar() {
    let mut holiday = sample_event(Vec::new());
    holiday.is_read_only = true;
    assert!(holiday.attendees[0].is_self && holiday.attendees[0].is_organizer);

    let off_availability = CalendarLabels::from_calendars(vec![holidays_calendar(9, 1)]);
    assert_eq!(ToolEventRole::of(&holiday, &off_availability), None);

    let on_availability = CalendarLabels::from_calendars(vec![VisibleCalendar {
        contributes_to_availability: true,
        ..holidays_calendar(9, 1)
    }]);
    assert_eq!(
        ToolEventRole::of(&holiday, &on_availability),
        None,
        "counting a calendar as busy time does not make the user its organizer"
    );
}

/// The copy rules add guests from the copy the user organizes, so that copy
/// keeps its role off availability and when a read-only calendar shows the
/// meeting too.
#[test]
fn role_keeps_the_organizer_of_a_writable_copy() {
    let own = VisibleCalendar {
        contributes_to_availability: false,
        ..visible_calendar(9, 1, "[email protected]", "Owner")
    };
    let labels = CalendarLabels::from_calendars(vec![own, holidays_calendar(12, 1)]);
    let mut event = sample_event(Vec::new());
    event.sources = vec![
        source_copy(9, "Standup"),
        crate::domain::models::CalendarEventSourceContent {
            is_read_only: true,
            ..source_copy(12, "Standup")
        },
    ];

    assert_eq!(
        ToolEventRole::of(&event, &labels),
        Some(ToolEventRole::Organizer)
    );
}

#[tokio::test]
async fn list_gives_a_read_only_calendars_event_no_role() {
    let organized = sample_event(Vec::new());
    let mut holiday = sample_event(Vec::new());
    holiday.id = Uuid::from_u128(8);
    holiday.ical_uid = "uid-holiday".to_string();
    holiday.calendar_id = Some(Uuid::from_u128(12));
    holiday.attendees.truncate(1);
    holiday.is_read_only = true;
    let mutations = MockMutations {
        calendars: Mutex::new(vec![
            visible_calendar(9, 1, "[email protected]", "Owner"),
            holidays_calendar(12, 1),
        ]),
        ..Default::default()
    };
    let occurrences = MockOccurrences {
        rows: Mutex::new(vec![
            (organized.clone(), occurrence_of(&organized, "k-1", false)),
            (holiday.clone(), occurrence_of(&holiday, "k-1", false)),
        ]),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(mutations, occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 21, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();

    assert_eq!(response.events[0].my_role, Some(ToolEventRole::Organizer));
    assert_eq!(response.events[1].my_role, None);
    assert!(
        response
            .summary
            .contains("outside the user's schedule (United States holidays)"),
        "{}",
        response.summary
    );
}

/// Availability counts each copy, so the canonical copy's calendar alone
/// cannot say the event is off the user's schedule.
#[test]
fn any_copy_on_the_schedule_puts_an_event_on_it() {
    let mut primary = visible_calendar(9, 1, "[email protected]", "Owner");
    primary.contributes_to_availability = false;
    let labels = CalendarLabels::from_calendars(vec![
        primary,
        visible_calendar(10, 1, "[email protected]", "Personal"),
    ]);
    let mut event = sample_event(Vec::new());
    assert_eq!(labels.event_on_schedule(&event), Some(false));

    event.sources = vec![source_copy(9, "Standup"), source_copy(10, "Standup")];
    assert_eq!(labels.event_on_schedule(&event), Some(true));
}

#[tokio::test]
async fn list_names_a_colleagues_calendar_and_keeps_the_inbox() {
    let mut event = sample_event(Vec::new());
    event.attendees.clear();
    event.viewer_can = ViewerCapabilities {
        organize: true,
        ..ViewerCapabilities::NONE
    };
    let mut shared = visible_calendar(9, 1, "[email protected]", "[email protected]");
    shared.contributes_to_availability = false;
    let mutations = MockMutations {
        calendars: Mutex::new(vec![shared]),
        ..Default::default()
    };
    let occurrences = MockOccurrences {
        rows: Mutex::new(vec![(event.clone(), occurrence_of(&event, "k-1", false))]),
        status: CalendarSyncStatus::Ready,
        copies: Mutex::new(Vec::new()),
    };
    let (_, context) = context(mutations, occurrences);

    let tool = ListCalendarEvents {
        start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
        end: Utc.with_ymd_and_hms(2026, 8, 21, 0, 0, 0).unwrap(),
    };
    let response = tool.call(context, request_context()).await.unwrap();

    let listed = &response.events[0];
    assert_eq!(
        listed.calendar_name.as_deref(),
        Some("[email protected]")
    );
    assert_eq!(listed.contributes_to_availability, Some(false));
    assert_eq!(listed.inbox.as_deref(), Some("[email protected]"));
    assert_eq!(listed.my_role, None);
    assert!(
        response
            .summary
            .contains("outside the user's schedule ([email protected])"),
        "{}",
        response.summary
    );
}

#[tokio::test]
async fn update_result_names_the_copy_it_changed() {
    let mutations = MockMutations {
        calendars: Mutex::new(vec![visible_calendar(9, 1, "[email protected]", "Owner")]),
        ..Default::default()
    };
    let (_, context) = context(mutations, empty_occurrences());

    let tool = UpdateCalendarEvent {
        event_id: Uuid::from_u128(7),
        calendar_id: None,
        inbox: None,
        scope: UpdateScopeInput::All,
        recurrence_id: None,
        title: Some("Renamed".to_string()),
        description: None,
        location: None,
        time: None,
        attendees: None,
        recurrence_lines: None,
        conference: None,
        reminders: None,
        rsvp: None,
        out_of_office: None,
        guest_policy: None,
    };
    let result = tool.call(context, request_context()).await.unwrap();

    assert_eq!(result.inbox.as_deref(), Some("[email protected]"));
    assert_eq!(result.calendar_name.as_deref(), Some("Owner"));
    assert_eq!(result.my_role, Some(ToolEventRole::Organizer));
}