const { Promotion } = require('../models');
const { Op } = require('sequelize');

class PromotionController {
  async getAll(req, res, next) {
    try {
      const promotions = await Promotion.findAll({
        order: [['start_date', 'DESC']],
      });
      res.json({ promotions });
    } catch (error) {
      next(error);
    }
  }

  async getActive(req, res, next) {
    try {
      const promotions = await Promotion.findAll({
        where: {
          is_active: true,
          start_date: { [Op.lte]: new Date() },
          end_date: { [Op.gte]: new Date() },
        },
        order: [['end_date', 'ASC']],
      });
      res.json({ promotions });
    } catch (error) {
      next(error);
    }
  }

  async getById(req, res, next) {
    try {
      const promotion = await Promotion.findByPk(req.params.id);
      if (!promotion) {
        return res.status(404).json({ error: 'Promotion not found' });
      }
      res.json({ promotion });
    } catch (error) {
      next(error);
    }
  }

  async getByCode(req, res, next) {
    try {
      const promotion = await Promotion.findOne({
        where: {
          promo_code: req.params.code,
          is_active: true,
          start_date: { [Op.lte]: new Date() },
          end_date: { [Op.gte]: new Date() },
        },
      });
      if (!promotion) {
        return res.status(404).json({ error: 'Invalid or expired promo code' });
      }
      res.json({ promotion });
    } catch (error) {
      next(error);
    }
  }

  async create(req, res, next) {
    try {
      const promotion = await Promotion.create(req.body);
      res.status(201).json({ promotion });
    } catch (error) {
      next(error);
    }
  }

  async update(req, res, next) {
    try {
      const promotion = await Promotion.findByPk(req.params.id);
      if (!promotion) {
        return res.status(404).json({ error: 'Promotion not found' });
      }
      await promotion.update(req.body);
      res.json({ promotion });
    } catch (error) {
      next(error);
    }
  }

  async remove(req, res, next) {
    try {
      const promotion = await Promotion.findByPk(req.params.id);
      if (!promotion) {
        return res.status(404).json({ error: 'Promotion not found' });
      }
      promotion.is_active = false;
      await promotion.save();
      res.json({ message: 'Promotion deactivated' });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new PromotionController();
