import type { Express, Request, Response } from "express";
import type { IStorage } from './storage.js';
import { EmailScheduler } from './email-scheduler.js';
import { EmailNotificationService } from './email-service.js';

// Global email scheduler instance
let emailScheduler: EmailScheduler | null = null;

export function setupEmailRoutes(app: Express, storage: IStorage) {
  // Initialize email scheduler
  if (!emailScheduler) {
    emailScheduler = new EmailScheduler(storage);
    emailScheduler.start().then(() => {
      console.log('✓ Email notification scheduler started successfully');
    }).catch(error => {
      console.error('✗ Email scheduler startup failed:', error);
    });
  }

  // Email notification system management endpoints (Admin only)
  app.get('/api/email/settings', async (req: Request, res: Response) => {
    try {
      const userId = req.session?.userId;
      if (!userId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const user = await storage.getUser(userId);
      if (!user || !user.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      const settings = await storage.getEmailNotificationSettings();
      res.json(settings);
    } catch (error) {
      console.error('Error fetching email settings:', error);
      res.status(500).json({ error: 'Failed to fetch email settings' });
    }
  });

  app.put('/api/email/settings', async (req: Request, res: Response) => {
    try {
      const userId = req.session?.userId;
      if (!userId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const user = await storage.getUser(userId);
      if (!user || !user.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      await storage.updateEmailNotificationSettings(req.body);
      res.json({ success: true, message: 'Email settings updated successfully' });
    } catch (error) {
      console.error('Error updating email settings:', error);
      res.status(500).json({ error: 'Failed to update email settings' });
    }
  });

  app.post('/api/email/test', async (req: Request, res: Response) => {
    try {
      const userId = req.session?.userId;
      if (!userId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const user = await storage.getUser(userId);
      if (!user || !user.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      const emailService = new EmailNotificationService(storage);
      const success = await emailService.testConnection();
      
      res.json({ 
        success, 
        message: success ? 'Email test successful - check manager@tatacommons.com' : 'Email test failed - check logs' 
      });
    } catch (error) {
      console.error('Error testing email connection:', error);
      res.status(500).json({ error: 'Failed to test email connection' });
    }
  });

  app.post('/api/email/digest/trigger', async (req: Request, res: Response) => {
    try {
      const userId = req.session?.userId;
      if (!userId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const user = await storage.getUser(userId);
      if (!user || !user.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      if (!emailScheduler) {
        return res.status(500).json({ error: 'Email scheduler not initialized' });
      }

      const { targetUserId } = req.body;
      
      const stats = await emailScheduler.triggerManualDigest(targetUserId);
      
      res.json({ 
        success: true, 
        stats,
        message: `Manual digest completed: ${stats.sent} sent, ${stats.failed} failed, ${stats.skipped} skipped`
      });
    } catch (error) {
      console.error('Error triggering manual digest:', error);
      res.status(500).json({ error: 'Failed to trigger manual digest' });
    }
  });

  app.get('/api/email/logs', async (req: Request, res: Response) => {
    try {
      const userId = req.session?.userId;
      if (!userId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const user = await storage.getUser(userId);
      if (!user || !user.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      const limit = parseInt(req.query.limit as string) || 50;
      const logs = await storage.getEmailLogs(limit);
      
      res.json(logs);
    } catch (error) {
      console.error('Error fetching email logs:', error);
      res.status(500).json({ error: 'Failed to fetch email logs' });
    }
  });

  app.get('/api/email/status', async (req: Request, res: Response) => {
    try {
      const userId = req.session?.userId;
      if (!userId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const user = await storage.getUser(userId);
      if (!user || !user.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      const settings = await storage.getEmailNotificationSettings();
      const today = new Date().toLocaleDateString('en-CA');
      const stats = await storage.getEmailDigestStats(today);
      
      res.json({
        schedulerRunning: emailScheduler !== null,
        settings: settings,
        todayStats: stats,
        hasApiKey: !!process.env.SENDGRID_API_KEY
      });
    } catch (error) {
      console.error('Error fetching email status:', error);
      res.status(500).json({ error: 'Failed to fetch email status' });
    }
  });

  // Email digest preview for testing
  app.get('/api/email/preview/:userId', async (req: Request, res: Response) => {
    try {
      const adminUserId = req.session?.userId;
      if (!adminUserId) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      const adminUser = await storage.getUser(adminUserId);
      if (!adminUser || !adminUser.roles?.includes('ROLE_ADMIN')) {
        return res.status(403).json({ error: 'Admin access required' });
      }

      const targetUserId = parseInt(req.params.userId);
      if (!emailScheduler) {
        return res.status(500).json({ error: 'Email scheduler not initialized' });
      }

      // Generate digest data without sending
      const user = await storage.getUser(targetUserId);
      if (!user) {
        return res.status(404).json({ error: 'User not found' });
      }

      const userName = user.showName || `${user.firstName} ${user.lastName}`.trim() || user.email;
      
      // Get messages from last 24 hours
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      
      const recentMessages = await storage.getRecentMessagesForUser(targetUserId, yesterday);
      const recentNotifications = await storage.getRecentNotificationsForUser(targetUserId, yesterday);

      const digestData = {
        userId: targetUserId,
        userName,
        userEmail: user.email,
        hasNewMessages: recentMessages.length > 0,
        hasNewNotifications: recentNotifications.length > 0,
        messageCount: recentMessages.length,
        notificationCount: recentNotifications.length,
        messages: recentMessages.map(msg => ({
          id: msg.id,
          sender: msg.sender_name || 'Unknown',
          itemName: msg.item_name || 'Unknown Item',
          excerpt: msg.text_content ? msg.text_content.substring(0, 80) + '...' : 'Voice message',
          createdAt: new Date(msg.created_at)
        })),
        notifications: recentNotifications.map(notif => ({
          id: notif.id,
          type: notif.type,
          title: notif.title,
          message: notif.message.substring(0, 120) + '...',
          createdAt: new Date(notif.created_at)
        }))
      };

      res.json(digestData);
    } catch (error) {
      console.error('Error generating email preview:', error);
      res.status(500).json({ error: 'Failed to generate email preview' });
    }
  });

  return emailScheduler;
}

export function getEmailScheduler(): EmailScheduler | null {
  return emailScheduler;
}

export function stopEmailScheduler(): void {
  if (emailScheduler) {
    emailScheduler.stop();
    emailScheduler = null;
  }
}