import { Request, Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import * as communicationService from '../services/communicationService';

export const sendWhatsApp = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const { leadId, recipient, message } = req.body;
        const result = await communicationService.sendWhatsApp(leadId, recipient, message, req.user.userId);
        res.status(201).json(result);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Failed to send WhatsApp' });
    }
};

export const sendSMS = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const { leadId, recipient, message } = req.body;
        const result = await communicationService.sendSMS(leadId, recipient, message, req.user.userId);
        res.status(201).json(result);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Failed to send SMS' });
    }
};

export const sendEmail = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const { leadId, recipient, subject, message } = req.body;
        const result = await communicationService.sendEmail(leadId, recipient, subject, message, req.user.userId);
        res.status(201).json(result);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Failed to send email' });
    }
};

export const getCommunications = async (req: Request, res: Response) => {
    try {
        const leadId = parseInt(req.params.leadId, 10);
        const communications = await communicationService.getCommunications(leadId);
        res.json(communications);
    } catch (error: any) {
        res.status(500).json({ error: error.message || 'Failed to get communications' });
    }
};
