const ContactMessage = require('../models/ContactMessage');
const { sanitizeInput, sanitizeEmail, sanitizePhone } = require('../utils/sanitize');

exports.getAllMessages = async (req, res) => {
  try {
    const filters = {};
    if (req.query.status) filters.status = sanitizeInput(req.query.status);

    const messages = await ContactMessage.getAll(filters);

    // Sanitize output data to prevent XSS when displaying
    const sanitizedMessages = messages.map(msg => ({
      ...msg,
      name: sanitizeInput(msg.name),
      email: sanitizeEmail(msg.email),
      phone: sanitizePhone(msg.phone),
      subject: sanitizeInput(msg.subject),
      message: sanitizeInput(msg.message)
    }));

    res.json({ data: sanitizedMessages });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.getMessageById = async (req, res) => {
  try {
    const message = await ContactMessage.getById(req.params.id);
    if (!message) {
      return res.status(404).json({ message: 'Mesaj bulunamadı' });
    }

    // Mark as read when viewed
    if (message.status === 'new') {
      await ContactMessage.updateStatus(req.params.id, 'read');
    }

    // Sanitize output data
    const sanitizedMessage = {
      ...message,
      name: sanitizeInput(message.name),
      email: sanitizeEmail(message.email),
      phone: sanitizePhone(message.phone),
      subject: sanitizeInput(message.subject),
      message: sanitizeInput(message.message)
    };

    res.json({ data: sanitizedMessage });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.createMessage = async (req, res) => {
  try {
    const { name, email, phone, subject, message } = req.body;

    if (!name || !message) {
      return res.status(400).json({ message: 'Ad ve mesaj zorunludur' });
    }

    // Sanitize inputs to prevent XSS
    const sanitizedData = {
      name: sanitizeInput(name),
      email: email ? sanitizeEmail(email) : null,
      phone: phone ? sanitizePhone(phone) : null,
      subject: subject ? sanitizeInput(subject) : null,
      message: sanitizeInput(message)
    };

    // Validate message length
    if (sanitizedData.message.length > 5000) {
      return res.status(400).json({ message: 'Mesaj çok uzun (max 5000 karakter)' });
    }

    const messageId = await ContactMessage.create(sanitizedData);
    res.status(201).json({
      message: 'Mesajınız başarıyla gönderildi',
      id: messageId
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.updateMessageStatus = async (req, res) => {
  try {
    const { status } = req.body;
    const updated = await ContactMessage.updateStatus(req.params.id, status);

    if (!updated) {
      return res.status(404).json({ message: 'Mesaj bulunamadı' });
    }

    res.json({ message: 'Mesaj durumu güncellendi' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.deleteMessage = async (req, res) => {
  try {
    const deleted = await ContactMessage.delete(req.params.id);

    if (!deleted) {
      return res.status(404).json({ message: 'Mesaj bulunamadı' });
    }

    res.json({ message: 'Mesaj silindi' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.getUnreadCount = async (req, res) => {
  try {
    const count = await ContactMessage.getUnreadCount();
    res.json({ count });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};
