import { Router } from 'express'; import { postGraph } from '../utils/index.ts'; import { acquireAppToken } from '../helper/msal.ts'; import { AuthManager } from '../auth/index.ts'; export default (auth?: AuthManager) => { const router = Router(); router.post('/', async (req, res) => { try { // Authentication handled via client credentials (resolveCredential + createMsalClient) // Validate request body const { subject, start, end, body, location, attendees, isOnlineMeeting } = req.body; if (!subject || !start || !end) { return res.status(400).json({ error: 'Missing required fields', required: ['subject', 'start', 'end'], hint: 'start and end must have dateTime and timeZone properties', }); } // Validate start and end format if (!start.dateTime || !start.timeZone) { return res.status(400).json({ error: 'Invalid start format', hint: 'start must have dateTime and timeZone properties', }); } if (!end.dateTime || !end.timeZone) { return res.status(400).json({ error: 'Invalid end format', hint: 'end must have dateTime and timeZone properties', }); } let token: string; try { token = await acquireAppToken(req, auth); } catch (err: any) { return res.status(401).json({ error: 'Failed to acquire access token', message: err?.message ?? String(err) }); } // Build event object const event: any = { subject, start, end, }; // Add optional fields if provided if (body) { event.body = { contentType: body.contentType || 'HTML', content: body.content || body, }; } if (location) { event.location = typeof location === 'string' ? { displayName: location } : location; } if (attendees && Array.isArray(attendees)) { event.attendees = attendees.map((attendee) => ({ emailAddress: typeof attendee === 'string' ? { address: attendee } : attendee.emailAddress, type: attendee.type || 'required', })); } if (isOnlineMeeting !== undefined) { event.isOnlineMeeting = isOnlineMeeting; } console.log('📅 Creating event:', event.subject); // Create event via Graph API const data = await postGraph('/me/events', token, event); res.status(201).json(data); } catch (err: any) { console.error('Create event error:', err.message); res.status(500).json({ error: err.message }); } }); return router; };