import { r as updateSlugSyncState } from "./sync-state-DMZgzpez.js";
import { n as appendInteraction } from "./interactions-writer-B8XAzdqR.js";
//#region src/sync/microsoft-calendar.ts
async function syncMicrosoftCalendar(opts) {
	const result = {
		synced: 0,
		skipped: 0,
		errors: []
	};
	const since = opts.since ?? /* @__PURE__ */ new Date(Date.now() - 720 * 60 * 60 * 1e3);
	const until = /* @__PURE__ */ new Date();
	const top = opts.maxResults ?? 50;
	const startStr = since.toISOString();
	const endStr = until.toISOString();
	const { readInteractions } = await import("./interactions-writer-B2y-73lh.js");
	const existing = await readInteractions(opts.dataDir, opts.slug).catch(() => "");
	let url = `https://graph.microsoft.com/v1.0/me/calendarView?startDateTime=${startStr}&endDateTime=${endStr}&$top=${top}&$select=id,subject,bodyPreview,start,end,attendees,organizer`;
	while (url) {
		let events;
		let nextLink;
		try {
			const res = await fetch(url, { headers: { Authorization: `Bearer ${opts.accessToken}` } });
			if (!res.ok) {
				result.errors.push(`Graph Calendar API error: ${res.status} ${res.statusText}`);
				break;
			}
			const data = await res.json();
			events = data.value ?? [];
			nextLink = data["@odata.nextLink"];
		} catch (err) {
			result.errors.push(`Network error: ${err.message}`);
			break;
		}
		for (const event of events) {
			const sourceRef = `microsoft://calendar/${event.id}`;
			if (existing.includes(sourceRef)) {
				result.skipped++;
				continue;
			}
			const date = event.start?.dateTime ? new Date(event.start.dateTime).toISOString().slice(0, 10) : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
			const attendeeNames = (event.attendees ?? []).map((a) => a.emailAddress?.name ?? a.emailAddress?.address ?? "unknown").join(", ");
			const organizer = event.organizer?.emailAddress?.name ?? event.organizer?.emailAddress?.address ?? "unknown";
			try {
				await appendInteraction(opts.dataDir, opts.slug, {
					date,
					type: "Meeting",
					with: attendeeNames || organizer,
					summary: `${event.subject ?? "(no subject)"}: ${event.bodyPreview?.slice(0, 200) ?? ""}`,
					nextSteps: [],
					sourceRef,
					synced: (/* @__PURE__ */ new Date()).toISOString(),
					direction: "inbound"
				});
				result.synced++;
			} catch (err) {
				result.errors.push(`Failed to append ${event.id}: ${err.message}`);
			}
		}
		url = nextLink;
	}
	if (result.synced > 0) updateSlugSyncState(opts.dataDir, opts.slug, { lastGmailSync: (/* @__PURE__ */ new Date()).toISOString() });
	return result;
}
//#endregion
export { syncMicrosoftCalendar };

//# sourceMappingURL=microsoft-calendar-BgVR8GDv.js.map