import { Router, Response } from 'express';
import { authenticateToken, AuthenticatedRequest } from '../middleware/auth';
import { emailService } from '../services/emailService';
import { logger } from '../utils/logger';

const router = Router();

// Manual email notification endpoint
router.post('/send/:docketEntryId', authenticateToken, async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { docketEntryId } = req.params;

    // Import prisma here to avoid circular dependency
    const { prisma } = await import('../index');

    // Get the docket entry with details
    const docketEntry = await prisma.docketEntry.findUnique({
      where: { id: parseInt(docketEntryId) },
      include: {
        documents: {
          orderBy: { displayOrder: 'asc' }
        }
      }
    });

    if (!docketEntry) {
      return res.status(404).json({
        success: false,
        message: 'Docket entry not found'
      });
    }

    // Send the email notification using the BCC functionality
    await emailService.notifySubscribersOfNewEntry(
      docketEntry.title,
      docketEntry.date.toISOString(),
      docketEntry.summary
    );

    logger.info(`Manual email notification sent for docket entry: ${docketEntry.title}`, {
      docketEntryId: docketEntry.id,
      adminUser: req.user?.username
    });

    res.json({
      success: true,
      message: 'Email notification sent successfully to all subscribers'
    });

  } catch (error) {
    logger.error('Failed to send manual email notification:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to send email notification'
    });
  }
});

export default router;
