const pool = require('../config/database');
const validator = require('validator');

// Subscribe to newsletter
const subscribe = async (req, res) => {
  try {
    const { email } = req.body;

    // Validation
    if (!email) {
      return res.status(400).json({
        success: false,
        message: 'E-posta adresi zorunludur'
      });
    }

    // Sanitize and validate email
    const sanitizedEmail = validator.normalizeEmail(email.trim().toLowerCase());

    if (!validator.isEmail(sanitizedEmail)) {
      return res.status(400).json({
        success: false,
        message: 'Geçersiz e-posta adresi'
      });
    }

    // Check if already subscribed
    const [existing] = await pool.execute(
      'SELECT id, status FROM newsletter_subscribers WHERE email = ?',
      [sanitizedEmail]
    );

    if (existing.length > 0) {
      if (existing[0].status === 'active') {
        return res.status(400).json({
          success: false,
          message: 'Bu e-posta adresi zaten kayıtlı'
        });
      } else {
        // Reactivate subscription
        await pool.execute(
          'UPDATE newsletter_subscribers SET status = ?, unsubscribed_at = NULL WHERE email = ?',
          ['active', sanitizedEmail]
        );
        return res.json({
          success: true,
          message: 'E-bülten aboneliğiniz yeniden aktif edildi'
        });
      }
    }

    // Get client IP and user agent
    const ipAddress = req.ip || req.connection.remoteAddress || null;
    const userAgent = req.get('User-Agent') || null;

    // Insert new subscription
    await pool.execute(
      `INSERT INTO newsletter_subscribers (email, ip_address, user_agent, status)
       VALUES (?, ?, ?, ?)`,
      [sanitizedEmail, ipAddress, userAgent, 'active']
    );

    res.status(201).json({
      success: true,
      message: 'E-bülten aboneliğiniz başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Error subscribing to newsletter:', error);

    // Handle duplicate key error
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({
        success: false,
        message: 'Bu e-posta adresi zaten kayıtlı'
      });
    }

    res.status(500).json({
      success: false,
      message: 'E-bülten kaydı sırasında hata oluştu'
    });
  }
};

// Unsubscribe from newsletter
const unsubscribe = async (req, res) => {
  try {
    const { email } = req.body;

    // Validation
    if (!email) {
      return res.status(400).json({
        success: false,
        message: 'E-posta adresi zorunludur'
      });
    }

    // Sanitize and validate email
    const sanitizedEmail = validator.normalizeEmail(email.trim().toLowerCase());

    if (!validator.isEmail(sanitizedEmail)) {
      return res.status(400).json({
        success: false,
        message: 'Geçersiz e-posta adresi'
      });
    }

    // Check if subscriber exists
    const [existing] = await pool.execute(
      'SELECT id, status FROM newsletter_subscribers WHERE email = ?',
      [sanitizedEmail]
    );

    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Bu e-posta adresi kayıtlı değil'
      });
    }

    if (existing[0].status === 'unsubscribed') {
      return res.status(400).json({
        success: false,
        message: 'Bu e-posta adresi zaten abonelikten çıkmış'
      });
    }

    // Update status to unsubscribed
    await pool.execute(
      'UPDATE newsletter_subscribers SET status = ?, unsubscribed_at = NOW() WHERE email = ?',
      ['unsubscribed', sanitizedEmail]
    );

    res.json({
      success: true,
      message: 'E-bülten aboneliğiniz iptal edildi'
    });
  } catch (error) {
    console.error('Error unsubscribing from newsletter:', error);
    res.status(500).json({
      success: false,
      message: 'Abonelik iptali sırasında hata oluştu'
    });
  }
};

// Get all subscribers (admin only)
const getAllSubscribers = async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT * FROM newsletter_subscribers';
    const params = [];

    if (status) {
      query += ' WHERE status = ?';
      params.push(status);
    }

    query += ' ORDER BY subscribed_at DESC';

    const [rows] = await pool.execute(query, params);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching subscribers:', error);
    res.status(500).json({
      success: false,
      message: 'Aboneler getirilirken hata oluştu'
    });
  }
};

// Get subscriber stats (admin only)
const getStats = async (req, res) => {
  try {
    const [stats] = await pool.execute(`
      SELECT
        COUNT(*) as total,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'unsubscribed' THEN 1 ELSE 0 END) as unsubscribed,
        COUNT(CASE WHEN DATE(subscribed_at) = CURDATE() THEN 1 END) as today,
        COUNT(CASE WHEN subscribed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as this_week,
        COUNT(CASE WHEN subscribed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as this_month
      FROM newsletter_subscribers
    `);

    res.json({ success: true, data: stats[0] });
  } catch (error) {
    console.error('Error fetching newsletter stats:', error);
    res.status(500).json({
      success: false,
      message: 'İstatistikler getirilirken hata oluştu'
    });
  }
};

// Delete subscriber (admin only)
const deleteSubscriber = async (req, res) => {
  try {
    const { id } = req.params;

    // Check if subscriber exists
    const [existing] = await pool.execute(
      'SELECT id FROM newsletter_subscribers WHERE id = ?',
      [id]
    );

    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Abone bulunamadı'
      });
    }

    await pool.execute('DELETE FROM newsletter_subscribers WHERE id = ?', [id]);
    res.json({ success: true, message: 'Abone başarıyla silindi' });
  } catch (error) {
    console.error('Error deleting subscriber:', error);
    res.status(500).json({
      success: false,
      message: 'Abone silinirken hata oluştu'
    });
  }
};

module.exports = {
  subscribe,
  unsubscribe,
  getAllSubscribers,
  getStats,
  deleteSubscriber
};
