// controllers/discountController.js
const { Discount, Product, Transaction, Customer } = require('../models');
const { Op } = require('sequelize');

// 🧾 Get all discounts
exports.getAllDiscounts = async (req, res) => {
  try {
    const { active } = req.query;
    const where = {};

    if (active === 'true') where.isActive = true;
    if (active === 'false') where.isActive = false;

    const discounts = await Discount.findAll({
      where,
      order: [['createdAt', 'DESC']],
      include: [
        { model: Product, as: 'product', attributes: ['id', 'name'] },
        { model: Customer, as: 'customer', attributes: ['id', 'firstName', 'lastName'] }
      ]
    });

    res.json(discounts);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching discounts', error: error.message });
  }
};

// 🔍 Get a discount by ID
exports.getDiscountById = async (req, res) => {
  try {
    const discount = await Discount.findByPk(req.params.id, {
      include: [
        { model: Product, as: 'product' },
        { model: Customer, as: 'customer' }
      ]
    });

    if (!discount) return res.status(404).json({ message: 'Discount not found' });

    res.json(discount);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching discount', error: error.message });
  }
};

// ➕ Create a new discount
exports.createDiscount = async (req, res) => {
  try {
    const {
      name,
      description,
      discountType,   // 'percentage' or 'fixed'
      value,
      startDate,
      endDate,
      productId,
      customerId,
      minPurchaseAmount,
      isActive
    } = req.body;

    const discount = await Discount.create({
      name,
      description,
      discountType,
      value,
      startDate,
      endDate,
      productId,
      customerId,
      minPurchaseAmount,
      isActive: isActive ?? true
    });

    res.status(201).json({ message: 'Discount created successfully', discount });
  } catch (error) {
    res.status(500).json({ message: 'Error creating discount', error: error.message });
  }
};

// ✏️ Update discount details
exports.updateDiscount = async (req, res) => {
  try {
    const discount = await Discount.findByPk(req.params.id);
    if (!discount) return res.status(404).json({ message: 'Discount not found' });

    await discount.update(req.body);
    res.json({ message: 'Discount updated successfully', discount });
  } catch (error) {
    res.status(500).json({ message: 'Error updating discount', error: error.message });
  }
};

// 🗑️ Delete (or deactivate) discount
exports.deleteDiscount = async (req, res) => {
  try {
    const discount = await Discount.findByPk(req.params.id);
    if (!discount) return res.status(404).json({ message: 'Discount not found' });

    // Soft delete (recommended)
    await discount.update({ isActive: false });

    res.json({ message: 'Discount deactivated successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Error deleting discount', error: error.message });
  }
};

// 💰 Apply discount to a product or transaction
exports.applyDiscount = async (req, res) => {
  try {
    const { discountCode, amount } = req.body;

    const discount = await Discount.findOne({
      where: {
        code: discountCode,
        isActive: true,
        startDate: { [Op.lte]: new Date() },
        endDate: { [Op.gte]: new Date() }
      }
    });

    if (!discount) {
      return res.status(404).json({ message: 'Discount code not valid or expired' });
    }

    let discountedAmount = amount;

    if (discount.discountType === 'percentage') {
      discountedAmount = amount - (amount * discount.value) / 100;
    } else if (discount.discountType === 'fixed') {
      discountedAmount = amount - discount.value;
    }

    if (discountedAmount < 0) discountedAmount = 0;

    res.json({
      message: 'Discount applied successfully',
      originalAmount: amount,
      discountValue: discount.value,
      discountType: discount.discountType,
      finalAmount: discountedAmount
    });
  } catch (error) {
    res.status(500).json({ message: 'Error applying discount', error: error.message });
  }
};
