// controllers/offerController.js
const { applyOfferCode } = require('../model/offerModel');

async function handleApplyOffer(req, res, next) {
  try {
    const { pmobile, uid, pemail, blk_ticket, divTotal, offerCode } = req.body;

    // basic validation
    if (![pmobile, uid, pemail, blk_ticket, divTotal, offerCode].every(Boolean)) {
      return res.status(400).json({ success: false, message: 'Missing required fields.' });
    }
    console.log('offer body',req.body)

    if (uid === 'Not Applicable') {
      return res.status(401).json({
        success: false,
        message: 'To apply this coupon, please login.'
      });
    }

    const result = await applyOfferCode({
      pmobile, uid, pemail, blk_ticket,
      divTotal: parseFloat(divTotal),
      offerCode: offerCode.trim()
    });

    if (!result.success) {
      return res.status(401).json(result);
    }

    res.status(200).json(result);

  } catch (err) {
    next(err);
  }
}

module.exports = { handleApplyOffer };
