import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { sendEmail } from '../../lib/email';

const prisma = new PrismaClient();

// GET /api/admin/marketing/campaigns
export const getCampaigns = async (req: Request, res: Response) => {
  try {
    const campaigns = await prisma.campaign.findMany({
      orderBy: { createdAt: 'desc' },
      take: 20,
    });

    const formattedCampaigns = campaigns.map(c => ({
      id: c.id,
      subject: c.subject,
      audience: c.audience === 'ALL' ? 'All Users' : c.audience,
      sent: c.sentCount,
      opened: "-", // Placeholder for future analytics
      status: c.status,
      date: c.createdAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
    }));

    res.json(formattedCampaigns);
  } catch (error) {
    console.error("Get Campaigns Error:", error);
    res.status(500).json({ error: "Failed to fetch campaigns" });
  }
};

// POST /api/admin/marketing/campaigns/send
export const sendCampaign = async (req: Request, res: Response) => {
  try {
    const { subject, body, recipient } = req.body;

    if (!subject || !body || !recipient) {
      return res.status(400).json({ error: "Missing required fields" });
    }

    // 1. Determine Audience & Fetch Emails
    let users = [];
    if (recipient === 'all') {
      users = await prisma.user.findMany({ select: { email: true, fullName: true } });
    } else if (recipient === 'newsletter') {
      // Assuming you have a boolean flag or a separate subscription model
      // For now, let's simulate fetching all users
      users = await prisma.user.findMany({ select: { email: true, fullName: true } });
    }
    // Add logic for VIP/Abandoned here...

    if (users.length === 0) {
      return res.status(400).json({ error: "No recipients found for this audience." });
    }

    // 2. Send Emails in Batches (to avoid memory issues/rate limits)
    // For production, use a Queue (BullMQ/Redis). For this MVP, we use Promise.all.
    const emailPromises = users.map(user => {
      // Personalize content
      const personalizedBody = body.replace('{{name}}', user.fullName?.split(' ')[0] || 'Customer');
      const personalizedHtml = `<p>${personalizedBody.replace(/\n/g, '<br>')}</p>`; // Simple HTML conversion

      return sendEmail({
        to: user.email,
        subject,
        html: personalizedHtml
      });
    });

    await Promise.all(emailPromises);

    // 3. Create Campaign Record
    const campaign = await prisma.campaign.create({
      data: {
        subject,
        body,
        audience: recipient.toUpperCase(),
        status: 'SENT',
        sentCount: users.length,
        sentAt: new Date(),
      }
    });

    res.json({ message: "Campaign sent successfully", campaign });

  } catch (error) {
    console.error("Send Campaign Error:", error);
    res.status(500).json({ error: "Failed to send campaign" });
  }
};