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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
const { validationResult } = require('express-validator');
const mongoose = require('mongoose');
const Document = require('../models/Document');
const fileService = require('../services/fileService');
const dueDateExtractionService = require('../services/dueDateExtractionService');
const calendarExportService = require('../services/calendarExportService');
const logger = require('../utils/logger');
const path = require('path');

class DocumentController {
  async uploadDocument(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      if (!req.file) {
        return res.status(400).json({
          success: false,
          error: 'No file uploaded'
        });
      }

      const file = req.file;
      const userId = req.user.id;

      // Validate file
      const validation = fileService.validateFile(file);
      if (!validation.isValid) {
        // Clean up uploaded file
        await fileService.deleteFile(file.path);
        return res.status(400).json({
          success: false,
          errors: validation.errors
        });
      }

      // Extract text from file
      logger.info('Extracting text from uploaded file', { 
        filename: file.filename,
        mimetype: file.mimetype,
        size: file.size 
      });

      const extractedData = await fileService.extractText(file.path, file.mimetype);

      // Create document record
      const documentData = {
        filename: file.filename,
        originalName: file.originalname,
        mimeType: file.mimetype,
        size: file.size,
        filePath: file.path,
        extractedText: extractedData.text,
        userId: userId,
        processingStatus: 'processing',
        type: req.body.type || 'other',
        courseCode: req.body.courseCode || '',
        courseName: req.body.courseName || '',
        semester: req.body.semester || '',
        year: req.body.year || new Date().getFullYear(),
        professor: req.body.professor || ''
      };

      // Add metadata if available
      if (extractedData.pages) {
        documentData.metadata = { pages: extractedData.pages };
      }

      const document = new Document(documentData);
      await document.save();

      // Extract due dates in the background
      try {
        const courseInfo = {
          courseCode: documentData.courseCode,
          semester: documentData.semester,
          year: documentData.year
        };

        const extractedDueDates = await dueDateExtractionService.extractDueDatesWithCourseContext(
          extractedData.text,
          courseInfo
        );

        // Validate and add due dates to document
        const validatedDueDates = dueDateExtractionService.validateExtractedDates(extractedDueDates);
        
        if (validatedDueDates.length > 0) {
          document.dueDates = validatedDueDates;
        }

        document.processingStatus = 'completed';
        await document.save();

        logger.info('Due dates extracted and saved', { 
          documentId: document._id,
          dueDatesCount: validatedDueDates.length 
        });

      } catch (extractionError) {
        logger.error('Due date extraction failed:', extractionError);
        document.processingStatus = 'completed';
        document.processingErrors = [extractionError.message];
        await document.save();
      }

      logger.info('Document uploaded successfully', { 
        documentId: document._id,
        userId: userId,
        filename: file.originalname 
      });

      // Return document without file path for security
      const responseDoc = document.toJSON();
      delete responseDoc.filePath;

      res.status(201).json({
        success: true,
        data: {
          document: responseDoc,
          extractedText: extractedData.text.substring(0, 500) + '...' // Preview
        },
        message: 'Document uploaded and processed successfully'
      });

    } catch (error) {
      logger.error('Document upload error:', error);
      
      // Clean up file if it exists
      if (req.file && req.file.path) {
        try {
          await fileService.deleteFile(req.file.path);
        } catch (cleanupError) {
          logger.error('Failed to cleanup file after error:', cleanupError);
        }
      }

      res.status(500).json({
        success: false,
        error: 'Failed to upload and process document'
      });
    }
  }

  async getDocuments(req, res) {
    try {
      const userId = req.user.id;
      const { type, courseCode, semester, year, page = 1, limit = 10 } = req.query;

      const options = {};
      if (type) options.type = type;
      if (courseCode) options.courseCode = courseCode;
      if (semester && year) {
        options.semester = semester;
        options.year = parseInt(year);
      }

      const documents = await Document.findByUser(userId, options)
        .limit(limit * 1)
        .skip((page - 1) * limit)
        .exec();

      const total = await Document.countDocuments({ userId, ...options });

      res.json({
        success: true,
        data: {
          documents,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total,
            pages: Math.ceil(total / limit)
          }
        }
      });

    } catch (error) {
      logger.error('Get documents error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch documents'
      });
    }
  }

  async getDocument(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id;

      const document = await Document.findOne({ _id: id, userId });

      if (!document) {
        return res.status(404).json({
          success: false,
          error: 'Document not found'
        });
      }

      // Increment view count
      await document.incrementViewCount();

      res.json({
        success: true,
        data: { document }
      });

    } catch (error) {
      logger.error('Get document error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch document'
      });
    }
  }

  async updateDocument(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id;
      const updates = req.body;

      // Only allow certain fields to be updated
      const allowedUpdates = ['type', 'courseCode', 'courseName', 'semester', 'year', 'professor', 'aiTags'];
      const filteredUpdates = {};
      
      allowedUpdates.forEach(field => {
        if (updates[field] !== undefined) {
          filteredUpdates[field] = updates[field];
        }
      });

      const document = await Document.findOneAndUpdate(
        { _id: id, userId },
        filteredUpdates,
        { new: true, runValidators: true }
      );

      if (!document) {
        return res.status(404).json({
          success: false,
          error: 'Document not found'
        });
      }

      logger.info('Document updated', { documentId: id, userId });

      res.json({
        success: true,
        data: { document },
        message: 'Document updated successfully'
      });

    } catch (error) {
      logger.error('Update document error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to update document'
      });
    }
  }

  async deleteDocument(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id;

      const document = await Document.findOne({ _id: id, userId });

      if (!document) {
        return res.status(404).json({
          success: false,
          error: 'Document not found'
        });
      }

      // Delete physical file
      if (document.filePath) {
        await fileService.deleteFile(document.filePath);
      }

      // Delete document record
      await Document.findByIdAndDelete(id);

      logger.info('Document deleted', { documentId: id, userId });

      res.json({
        success: true,
        message: 'Document deleted successfully'
      });

    } catch (error) {
      logger.error('Delete document error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to delete document'
      });
    }
  }

  async getUpcomingDueDates(req, res) {
    try {
      const userId = req.user.id;
      const { days = 30 } = req.query;

      const dueDates = await Document.findUpcomingDueDates(userId, parseInt(days));

      res.json({
        success: true,
        data: { dueDates }
      });

    } catch (error) {
      logger.error('Get upcoming due dates error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch upcoming due dates'
      });
    }
  }

  async addDueDate(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id;
      const dueDateData = req.body;

      const document = await Document.findOne({ _id: id, userId });

      if (!document) {
        return res.status(404).json({
          success: false,
          error: 'Document not found'
        });
      }

      await document.addDueDate(dueDateData);

      logger.info('Due date added to document', { documentId: id, userId });

      res.json({
        success: true,
        data: { document },
        message: 'Due date added successfully'
      });

    } catch (error) {
      logger.error('Add due date error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to add due date'
      });
    }
  }

  async searchDocuments(req, res) {
    try {
      const userId = req.user.id;
      const { q, page = 1, limit = 10 } = req.query;

      if (!q || q.trim().length < 3) {
        return res.status(400).json({
          success: false,
          error: 'Search query must be at least 3 characters'
        });
      }

      const documents = await Document.find({
        userId,
        $text: { $search: q }
      })
      .score({ score: { $meta: 'textScore' } })
      .sort({ score: { $meta: 'textScore' } })
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .exec();

      res.json({
        success: true,
        data: { documents }
      });

    } catch (error) {
      logger.error('Search documents error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to search documents'
      });
    }
  }

  async getUploadStats(req, res) {
    try {
      const userId = req.user.id;

      // Validate ObjectId format
      if (!mongoose.Types.ObjectId.isValid(userId)) {
        return res.status(400).json({
          success: false,
          error: 'Invalid user ID format'
        });
      }

      const stats = await Document.aggregate([
        { $match: { userId: new mongoose.Types.ObjectId(userId) } },
        {
          $group: {
            _id: null,
            totalDocuments: { $sum: 1 },
            totalSize: { $sum: '$size' },
            documentTypes: { $addToSet: '$type' },
            totalDueDates: { $sum: { $size: '$dueDates' } }
          }
        }
      ]);

      const fileStats = fileService.getUploadStats();

      res.json({
        success: true,
        data: {
          documents: stats[0] || {
            totalDocuments: 0,
            totalSize: 0,
            documentTypes: [],
            totalDueDates: 0
          },
          storage: fileStats
        }
      });

    } catch (error) {
      logger.error('Get upload stats error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch upload statistics'
      });
    }
  }

  async exportCalendar(req, res) {
    try {
      const userId = req.user.id;
      const { 
        course, 
        type, 
        startDate, 
        endDate, 
        minConfidence = 0.3,
        format = 'ics'
      } = req.query;

      // Get all due dates for the user
      const dueDates = await Document.findUpcomingDueDates(userId, 365); // Get all due dates for next year

      if (dueDates.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'No due dates found for calendar export'
        });
      }

      // Apply filters
      const filters = {
        course,
        type,
        startDate,
        endDate,
        minConfidence: parseFloat(minConfidence)
      };

      // Generate calendar file
      const calendarData = await calendarExportService.generateFilteredCalendar(dueDates, filters);

      // Set appropriate headers for calendar file
      const filename = `uga-academic-calendar-${new Date().toISOString().split('T')[0]}.ics`;
      
      res.setHeader('Content-Type', 'text/calendar; charset=utf-8');
      res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
      res.setHeader('Cache-Control', 'no-cache');

      logger.info('Calendar exported', { 
        userId, 
        dueDatesCount: dueDates.length,
        filters 
      });

      res.send(calendarData);

    } catch (error) {
      logger.error('Calendar export error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to export calendar'
      });
    }
  }
}

module.exports = new DocumentController();