const { Payment, Booking } = require('../models');
const { generatePaymentReference } = require('../services/ReferenceGenerator');

class PaymentController {
  async create(req, res, next) {
    try {
      const { booking_id, amount, payment_method, transaction_id, notes } = req.body;

      const booking = await Booking.findByPk(booking_id);
      if (!booking) {
        return res.status(404).json({ error: 'Booking not found' });
      }

      const paymentReference = generatePaymentReference();

      const payment = await Payment.create({
        booking_id,
        payment_reference: paymentReference,
        amount,
        payment_method,
        transaction_id,
        notes,
        payment_status: 'completed',
        payment_date: new Date(),
      });

      if (parseFloat(amount) >= parseFloat(booking.total_amount)) {
        booking.payment_status = 'fully_paid';
      } else if (parseFloat(amount) >= parseFloat(booking.deposit_amount)) {
        booking.payment_status = 'deposit_only';
      }

      await booking.save();

      res.status(201).json({ payment, booking });
    } catch (error) {
      next(error);
    }
  }

  async getByBooking(req, res, next) {
    try {
      const payments = await Payment.findAll({
        where: { booking_id: req.params.bookingId },
        order: [['created_at', 'DESC']],
      });
      res.json({ payments });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new PaymentController();
