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

const prisma = new PrismaClient();

// GET /api/admin/support/users?search=...
// Search users for the recipient dropdown
export const searchUsers = async (req: Request, res: Response) => {
  try {
    const { search } = req.query;

    if (!search || String(search).length < 2) {
      return res.json([]); // Return empty if search is too short
    }

    const users = await prisma.user.findMany({
      where: {
        OR: [
          { fullName: { contains: String(search), mode: 'insensitive' } },
          { email: { contains: String(search), mode: 'insensitive' } },
        ],
      },
      select: {
        id: true,
        fullName: true,
        email: true,
        image: true
      },
      take: 10,
    });

    // Map to match frontend expectations
    const formattedUsers = users.map(u => ({
      id: u.id,
      name: u.fullName || 'Unknown',
      email: u.email,
      image: u.image
    }));

    res.json(formattedUsers);
  } catch (error) {
    console.error('Search Users Error:', error);
    res.status(500).json({ error: 'Failed to search users' });
  }
};

// GET /api/admin/support/history
// Fetch recent email logs
export const getSupportHistory = async (req: Request, res: Response) => {
  try {
    const logs = await prisma.supportLog.findMany({
      take: 20,
      orderBy: { sentAt: 'desc' },
      include: {
        user: {
          select: { fullName: true, email: true }
        }
      }
    });

    const formattedLogs = logs.map(log => ({
      id: log.id,
      to: log.user.fullName || log.user.email,
      email: log.user.email,
      subject: log.subject,
      status: log.status,
      date: log.sentAt.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }),
    }));

    res.json(formattedLogs);
  } catch (error) {
    console.error('Get History Error:', error);
    res.status(500).json({ error: 'Failed to fetch history' });
  }
};

/// POST /api/admin/support/send
export const sendSupportEmail = async (req: Request, res: Response) => {
  try {
    const { userId, subject, message } = req.body;

    // 1. Validation
    if (!userId || !subject || !message) {
      return res.status(400).json({ error: 'Recipient, subject, and message are required.' });
    }

    // 2. Fetch User Details
    const user = await prisma.user.findUnique({ where: { id: userId } });
    if (!user || !user.email) {
        return res.status(404).json({ error: 'User not found or has no email' });
    }

    // 3. Send Email via SMTP
    const emailSuccess = await sendEmail({
      to: user.email,
      subject: subject,
      html: `<p>${message.replace(/\n/g, '<br>')}</p>`, // Basic HTML conversion
    });

    if (!emailSuccess) {
      return res.status(500).json({ error: 'Failed to send email via SMTP provider' });
    }

    // 4. Log to Database
    const log = await prisma.supportLog.create({
      data: {
        userId,
        subject,
        body: message,
        status: 'SENT',
        
      }
    });

    res.json({ message: 'Email sent successfully', log });

  } catch (error) {
    console.error('Send Email Controller Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};