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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
const UGAEvent = require('../models/UGAEvent');
const ugaLocalistService = require('./ugaLocalistService');
const ugaEventsScrapingService = require('./ugaEventsScrapingService');
const logger = require('../utils/logger');
const { redisUtils } = require('../utils/redis');
const cron = require('node-cron');

class UGAEventsService {
  constructor() {
    this.syncInProgress = false;
    this.lastSyncTime = null;
    this.syncInterval = '0 */6 * * *'; // Every 6 hours
    this.cacheTimeout = 1800; // 30 minutes

    // Start scheduled sync
    this.initializeScheduledSync();
  }

  // Initialize scheduled data synchronization
  initializeScheduledSync() {
    // Sync every 6 hours
    cron.schedule(this.syncInterval, async () => {
      logger.info('Starting scheduled UGA events sync');
      await this.syncAllEvents();
    });

    // Initial sync on startup (delayed)
    setTimeout(async () => {
      logger.info('Starting initial UGA events sync');
      await this.syncAllEvents();
    }, 30000); // 30 second delay
  }

  // Main method to sync all events from all sources
  async syncAllEvents(forceSync = false) {
    if (this.syncInProgress && !forceSync) {
      logger.info('Sync already in progress, skipping');
      return { success: false, message: 'Sync already in progress' };
    }

    try {
      this.syncInProgress = true;
      logger.info('Starting comprehensive UGA events sync');

      const results = {
        localist: { success: false, count: 0, errors: [] },
        registrar: { success: false, count: 0, errors: [] },
        totalProcessed: 0,
        totalSaved: 0,
        totalUpdated: 0,
        totalErrors: 0
      };

      // 1. Sync Localist events
      try {
        const localistResult = await this.syncLocalistEvents();
        results.localist = localistResult;
        results.totalProcessed += localistResult.count;
      } catch (error) {
        logger.error('Error syncing Localist events:', error.message);
        results.localist.errors.push(error.message);
      }

      // 2. Sync Registrar data
      try {
        const registrarResult = await this.syncRegistrarEvents();
        results.registrar = registrarResult;
        results.totalProcessed += registrarResult.count;
      } catch (error) {
        logger.error('Error syncing Registrar events:', error.message);
        results.registrar.errors.push(error.message);
      }

      // 3. Clean up old events
      const cleanupResult = await this.cleanupOldEvents();
      results.cleanupCount = cleanupResult.deletedCount;

      // 4. Update cache
      await this.updateCache();

      this.lastSyncTime = new Date();
      results.syncTime = this.lastSyncTime;

      logger.info('UGA events sync completed', results);
      return { success: true, results };

    } catch (error) {
      logger.error('Error in comprehensive sync:', error.message);
      return { success: false, error: error.message };
    } finally {
      this.syncInProgress = false;
    }
  }

  // Sync events from Localist API
  async syncLocalistEvents() {
    logger.info('Syncing Localist events');

    try {
      // Fetch upcoming events (next 6 months)
      const localistResult = await ugaLocalistService.fetchUpcomingEvents(180, 200);

      if (!localistResult.success) {
        return { success: false, count: 0, errors: [localistResult.error] };
      }

      let savedCount = 0;
      let updatedCount = 0;
      const errors = [];

      for (const eventData of localistResult.data) {
        try {
          const result = await this.saveOrUpdateEvent(eventData);
          if (result.created) {
            savedCount++;
          } else if (result.updated) {
            updatedCount++;
          }
        } catch (error) {
          errors.push(`Error processing event ${eventData.title}: ${error.message}`);
          logger.warn('Error processing Localist event:', error.message);
        }
      }

      return {
        success: true,
        count: localistResult.data.length,
        saved: savedCount,
        updated: updatedCount,
        errors: errors
      };

    } catch (error) {
      logger.error('Error in Localist sync:', error.message);
      return { success: false, count: 0, errors: [error.message] };
    }
  }

  // Sync events from Registrar scraping
  async syncRegistrarEvents() {
    logger.info('Syncing Registrar events');

    try {
      const registrarResult = await ugaEventsScrapingService.scrapeAllRegistrarData();

      if (!registrarResult.success) {
        return { success: false, count: 0, errors: ['Registrar scraping failed'] };
      }

      let savedCount = 0;
      let updatedCount = 0;
      const errors = [];

      for (const eventData of registrarResult.data) {
        try {
          // Ensure proper format for registrar events
          const formattedEvent = this.formatRegistrarEvent(eventData);
          const result = await this.saveOrUpdateEvent(formattedEvent);

          if (result.created) {
            savedCount++;
          } else if (result.updated) {
            updatedCount++;
          }
        } catch (error) {
          errors.push(`Error processing registrar event ${eventData.title}: ${error.message}`);
          logger.warn('Error processing Registrar event:', error.message);
        }
      }

      return {
        success: true,
        count: registrarResult.data.length,
        saved: savedCount,
        updated: updatedCount,
        errors: errors
      };

    } catch (error) {
      logger.error('Error in Registrar sync:', error.message);
      return { success: false, count: 0, errors: [error.message] };
    }
  }

  // Format registrar event data to match our schema
  formatRegistrarEvent(eventData) {
    return {
      ...eventData,
      location: eventData.location || {
        name: 'University of Georgia',
        isVirtual: false
      },
      links: eventData.links || [],
      images: eventData.images || [],
      tags: eventData.tags || [],
      keywords: eventData.keywords || [],
      organizer: eventData.organizer || {
        name: 'UGA Office of the Registrar',
        department: 'Registrar'
      },
      analytics: {
        views: 0,
        clicks: 0,
        shares: 0,
        registrations: 0
      }
    };
  }

  // Save or update an event in the database
  async saveOrUpdateEvent(eventData) {
    try {
      // Create a unique identifier for deduplication
      const uniqueKey = this.createEventUniqueKey(eventData);

      // Look for existing event
      let existingEvent = null;

      if (eventData.metadata?.sourceId) {
        existingEvent = await UGAEvent.findOne({
          'metadata.sourceId': eventData.metadata.sourceId,
          'metadata.source': eventData.metadata.source
        });
      }

      if (!existingEvent) {
        // Try to find by title and date (for events without sourceId)
        existingEvent = await UGAEvent.findOne({
          title: eventData.title,
          startDate: {
            $gte: new Date(eventData.startDate.getTime() - 24 * 60 * 60 * 1000), // 1 day before
            $lte: new Date(eventData.startDate.getTime() + 24 * 60 * 60 * 1000)  // 1 day after
          }
        });
      }

      if (existingEvent) {
        // Update existing event
        const hasChanges = this.hasEventChanged(existingEvent, eventData);

        if (hasChanges) {
          Object.assign(existingEvent, eventData);
          existingEvent.metadata.lastUpdated = new Date();
          await existingEvent.save();

          logger.debug(`Updated event: ${eventData.title}`);
          return { updated: true, created: false, event: existingEvent };
        } else {
          // Just update sync time
          existingEvent.metadata.lastSynced = new Date();
          await existingEvent.save();

          return { updated: false, created: false, event: existingEvent };
        }
      } else {
        // Create new event
        const newEvent = new UGAEvent(eventData);
        await newEvent.save();

        logger.debug(`Created event: ${eventData.title}`);
        return { updated: false, created: true, event: newEvent };
      }

    } catch (error) {
      logger.error('Error saving/updating event:', error.message);
      throw error;
    }
  }

  // Create unique key for event deduplication
  createEventUniqueKey(eventData) {
    const title = eventData.title?.toLowerCase().replace(/\s+/g, '') || '';
    const date = eventData.startDate?.toISOString().split('T')[0] || '';
    const source = eventData.metadata?.source || '';

    return `${source}-${title}-${date}`;
  }

  // Check if event data has changed
  hasEventChanged(existingEvent, newEventData) {
    const fields = ['title', 'description', 'startDate', 'endDate', 'location'];

    for (const field of fields) {
      if (field === 'startDate' || field === 'endDate') {
        const existingDate = existingEvent[field]?.getTime();
        const newDate = newEventData[field]?.getTime();
        if (existingDate !== newDate) {
          return true;
        }
      } else if (field === 'location') {
        const existingLocation = JSON.stringify(existingEvent[field] || {});
        const newLocation = JSON.stringify(newEventData[field] || {});
        if (existingLocation !== newLocation) {
          return true;
        }
      } else {
        if (existingEvent[field] !== newEventData[field]) {
          return true;
        }
      }
    }

    return false;
  }

  // Clean up old events
  async cleanupOldEvents() {
    try {
      const sixMonthsAgo = new Date();
      sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);

      const result = await UGAEvent.deleteMany({
        endDate: { $lt: sixMonthsAgo },
        eventType: { $ne: 'academic-calendar' } // Keep academic calendar events
      });

      logger.info(`Cleaned up ${result.deletedCount} old events`);
      return result;

    } catch (error) {
      logger.error('Error cleaning up old events:', error.message);
      return { deletedCount: 0 };
    }
  }

  // Update cache with fresh data
  async updateCache() {
    try {
      // Cache upcoming events
      const upcomingEvents = await this.getUpcomingEvents(50);
      await redisUtils.setex('uga:events:upcoming', this.cacheTimeout, upcomingEvents);

      // Cache important dates
      const importantDates = await this.getImportantDates();
      await redisUtils.setex('uga:events:important', this.cacheTimeout, importantDates);

      // Cache events by category
      const categories = ['academics', 'athletics', 'arts', 'career-services', 'student-affairs'];
      for (const category of categories) {
        const categoryEvents = await this.getEventsByCategory(category, 30);
        await redisUtils.setex(`uga:events:category:${category}`, this.cacheTimeout, categoryEvents);
      }

      logger.info('Updated events cache');

    } catch (error) {
      logger.error('Error updating cache:', error.message);
    }
  }

  // Public API methods

  // Get upcoming events
  async getUpcomingEvents(limit = 50, eventTypes = []) {
    try {
      const cacheKey = `uga:events:upcoming:${limit}:${eventTypes.join(',')}`;
      const cached = await redisUtils.get(cacheKey);
      if (cached) {
        return { success: true, data: cached, source: 'cache' };
      }

      const events = await UGAEvent.findUpcoming(limit, eventTypes);

      await redisUtils.setex(cacheKey, 900, events); // 15 minutes cache
      return { success: true, data: events, source: 'database' };

    } catch (error) {
      logger.error('Error getting upcoming events:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Get events by date range
  async getEventsByDateRange(startDate, endDate, options = {}) {
    try {
      const events = await UGAEvent.findByDateRange(startDate, endDate, options);
      return { success: true, data: events };

    } catch (error) {
      logger.error('Error getting events by date range:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Get important dates
  async getImportantDates(semester = null, year = null) {
    try {
      const cacheKey = `uga:events:important:${semester}:${year}`;
      const cached = await redisUtils.get(cacheKey);
      if (cached) {
        return { success: true, data: cached, source: 'cache' };
      }

      const events = await UGAEvent.findImportantDates(semester, year);

      await redisUtils.setex(cacheKey, 1800, events); // 30 minutes cache
      return { success: true, data: events, source: 'database' };

    } catch (error) {
      logger.error('Error getting important dates:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Get events by category
  async getEventsByCategory(category, days = 30) {
    try {
      const startDate = new Date();
      const endDate = new Date();
      endDate.setDate(endDate.getDate() + days);

      const events = await UGAEvent.findByDateRange(startDate, endDate, {
        categories: [category]
      });

      return { success: true, data: events };

    } catch (error) {
      logger.error('Error getting events by category:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Get events by audience
  async getEventsByAudience(audience, limit = 20) {
    try {
      const events = await UGAEvent.findByAudience(audience, limit);
      return { success: true, data: events };

    } catch (error) {
      logger.error('Error getting events by audience:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Search events
  async searchEvents(query, options = {}) {
    try {
      const events = await UGAEvent.searchEvents(query, options);
      return { success: true, data: events };

    } catch (error) {
      logger.error('Error searching events:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Get event statistics
  async getEventStatistics() {
    try {
      const cacheKey = 'uga:events:statistics';
      const cached = await redisUtils.get(cacheKey);
      if (cached) {
        return { success: true, data: cached, source: 'cache' };
      }

      const now = new Date();
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);

      const stats = await UGAEvent.aggregate([
        {
          $facet: {
            totalEvents: [{ $count: 'count' }],
            upcomingEvents: [
              { $match: { startDate: { $gte: now }, status: 'published' } },
              { $count: 'count' }
            ],
            thisMonthEvents: [
              { $match: { startDate: { $gte: startOfMonth, $lte: endOfMonth } } },
              { $count: 'count' }
            ],
            eventsByType: [
              { $group: { _id: '$eventType', count: { $sum: 1 } } },
              { $sort: { count: -1 } }
            ],
            eventsByCategory: [
              { $group: { _id: '$category', count: { $sum: 1 } } },
              { $sort: { count: -1 } }
            ],
            importantDates: [
              { $match: { isImportantDate: true, startDate: { $gte: now } } },
              { $count: 'count' }
            ]
          }
        }
      ]);

      const result = {
        totalEvents: stats[0].totalEvents[0]?.count || 0,
        upcomingEvents: stats[0].upcomingEvents[0]?.count || 0,
        thisMonthEvents: stats[0].thisMonthEvents[0]?.count || 0,
        importantDates: stats[0].importantDates[0]?.count || 0,
        eventsByType: stats[0].eventsByType,
        eventsByCategory: stats[0].eventsByCategory,
        lastSyncTime: this.lastSyncTime
      };

      await redisUtils.setex(cacheKey, 1800, result); // 30 minutes cache
      return { success: true, data: result, source: 'database' };

    } catch (error) {
      logger.error('Error getting event statistics:', error.message);
      return { success: false, error: error.message };
    }
  }

  // Get sync status
  getSyncStatus() {
    return {
      syncInProgress: this.syncInProgress,
      lastSyncTime: this.lastSyncTime,
      nextSyncEstimate: this.getNextSyncTime()
    };
  }

  // Calculate next sync time
  getNextSyncTime() {
    if (!this.lastSyncTime) {
      return new Date();
    }

    const nextSync = new Date(this.lastSyncTime);
    nextSync.setHours(nextSync.getHours() + 6); // Every 6 hours
    return nextSync;
  }

  // Manual sync trigger
  async triggerManualSync() {
    if (this.syncInProgress) {
      return { success: false, message: 'Sync already in progress' };
    }

    logger.info('Manual sync triggered');
    return await this.syncAllEvents(true);
  }

  // Test all connections
  async testConnections() {
    const results = {
      localist: await ugaLocalistService.testConnection(),
      scraping: await ugaEventsScrapingService.testScrapingConnection(),
      database: await this.testDatabaseConnection()
    };

    return results;
  }

  // Test database connection
  async testDatabaseConnection() {
    try {
      await UGAEvent.findOne().limit(1);
      return { success: true, message: 'Database connection successful' };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
}

module.exports = new UGAEventsService();