import { Response, NextFunction } from 'express';
import prisma from '../utils/db';
import { AuthRequest } from '../middleware/auth.middleware';
import { MailService } from '../services/mail.service';

export class NotificationController {
  private mailService = new MailService();

  public sendAssetAnnouncement = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const { title, message, targetOrgIds, assetIds } = req.body;
      if (!title || !message) {
        return res.status(400).json({ error: 'Title and message are required' });
      }

      let senderEmail = 'admin@tech4biz.com';
      if (req.user?.userId) {
        const adminUser = await prisma.user.findUnique({ where: { id: req.user.userId }, select: { email: true } });
        if (adminUser?.email) senderEmail = adminUser.email;
      }

      // Log notification record
      const notification = await prisma.assetNotification.create({
        data: {
          title,
          message,
          sentBy: senderEmail,
          targetOrgIds: Array.isArray(targetOrgIds) ? targetOrgIds : ['ALL'],
          assetIds: Array.isArray(assetIds) ? assetIds : [],
        }
      });

      // Find recipient users
      const userWhere: any = { role: 'PARTNER_USER' };
      if (Array.isArray(targetOrgIds) && targetOrgIds.length > 0 && !targetOrgIds.includes('ALL')) {
        userWhere.organizationId = { in: targetOrgIds };
      }

      const partnerUsers = await prisma.user.findMany({
        where: userWhere,
        select: { email: true }
      });

      const recipientEmails = partnerUsers.map(u => u.email).filter(Boolean);

      // Trigger email notifications asynchronously via mailService
      if (recipientEmails.length > 0) {
        this.mailService.sendCustomAnnouncement({
          recipients: recipientEmails,
          subject: `📢 Asset Announcement: ${title}`,
          messageBody: message,
        }).catch(err => console.error('Failed to dispatch announcement emails:', err));
      }

      res.status(201).json({
        message: 'Notification sent successfully',
        recipientsCount: recipientEmails.length,
        notification,
      });
    } catch (err) { next(err); }
  };

  public getNotificationLogs = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const logs = await prisma.assetNotification.findMany({
        orderBy: { createdAt: 'desc' },
        take: 50,
      });
      res.status(200).json(logs);
    } catch (err) { next(err); }
  };
}
