/** * Google Calendar Service * @author Descomplicar® | @link descomplicar.pt | @copyright 2026 */ import { google } from 'googleapis' const oauth2Client = new google.auth.OAuth2( '188617934470-pomrua9oj4459dk69jpv6qhvst9pd3f6.apps.googleusercontent.com', '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', 'https://developers.google.com/oauthplayground' ) oauth2Client.setCredentials({ refresh_token: '1//03AJOfA8x4_eyCgYIARAAGAMSNwF-L9Ir2hVygx8arVuZpZKJpqPsFpGCLo3pXJGC9rxpHnVw5Gki5cLWG7Ez64RcT0RFVItZ2fQ' }) const calendar = google.calendar({ version: 'v3', auth: oauth2Client }) interface CalendarEvent { titulo: string hora: string data?: string tipo: 'personal' | 'work' link: string } export async function getEvents(calendarId: string, timeMin: string, timeMax: string): Promise { try { const response = await calendar.events.list({ calendarId, timeMin, timeMax, singleEvents: true, orderBy: 'startTime', maxResults: 20 }) const events: CalendarEvent[] = [] const items = response.data.items || [] for (const event of items) { const start = event.start?.dateTime || event.start?.date if (!start) continue const startDate = new Date(start) const tipo = calendarId === 'primary' ? 'personal' : 'work' events.push({ titulo: event.summary || 'Sem título', hora: startDate.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' }), data: calendarId === 'primary' ? undefined : startDate.toLocaleDateString('pt-PT', { weekday: 'short', day: '2-digit', month: '2-digit' }), tipo, link: event.htmlLink || '#' }) } return events } catch (error) { console.error(`Calendar error (${calendarId}):`, error) return [] } } export async function getTodayEvents(): Promise { const today = new Date() today.setHours(0, 0, 0, 0) const tomorrow = new Date(today) tomorrow.setDate(tomorrow.getDate() + 1) const timeMin = today.toISOString() const timeMax = tomorrow.toISOString() const [personal, work] = await Promise.all([ getEvents('primary', timeMin, timeMax), getEvents('emanuel@descomplicar.pt', timeMin, timeMax) ]) return [...personal, ...work].sort((a, b) => a.hora.localeCompare(b.hora)) } export async function getWeekEvents(): Promise { const today = new Date() today.setHours(0, 0, 0, 0) const tomorrow = new Date(today) tomorrow.setDate(tomorrow.getDate() + 1) const nextSunday = new Date(today) nextSunday.setDate(today.getDate() + (7 - today.getDay())) nextSunday.setHours(23, 59, 59, 999) const timeMin = tomorrow.toISOString() const timeMax = nextSunday.toISOString() const [personal, work] = await Promise.all([ getEvents('primary', timeMin, timeMax), getEvents('emanuel@descomplicar.pt', timeMin, timeMax) ]) return [...personal, ...work].sort((a, b) => { const dateA = a.data + a.hora const dateB = b.data + b.hora return dateA.localeCompare(dateB) }) }