const { Booking, Payment, Customer } = require('../models');
const { Op, fn, col, literal } = require('sequelize');

class ReportController {
  async getDaily(req, res, next) {
    try {
      const date = req.query.date || new Date().toISOString().split('T')[0];

      const startOfDay = new Date(`${date}T00:00:00.000Z`);
      const endOfDay = new Date(`${date}T23:59:59.999Z`);

      const [bookings, payments, totalRevenue] = await Promise.all([
        Booking.count({
          where: { created_at: { [Op.between]: [startOfDay, endOfDay] } },
        }),
        Payment.findAll({
          where: {
            payment_date: { [Op.between]: [startOfDay, endOfDay] },
            payment_status: 'completed',
          },
        }),
        Payment.sum('amount', {
          where: {
            payment_date: { [Op.between]: [startOfDay, endOfDay] },
            payment_status: 'completed',
          },
        }),
      ]);

      const revenueByMethod = {};
      payments.forEach((p) => {
        revenueByMethod[p.payment_method] = (revenueByMethod[p.payment_method] || 0) + parseFloat(p.amount);
      });

      const byStatus = await Booking.findAll({
        attributes: ['booking_status', [fn('COUNT', col('id')), 'count']],
        where: { created_at: { [Op.between]: [startOfDay, endOfDay] } },
        group: ['booking_status'],
      });

      res.json({
        date,
        summary: {
          total_bookings: bookings,
          total_revenue: totalRevenue || 0,
          revenue_by_method: revenueByMethod,
        },
        bookings_by_status: byStatus,
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new ReportController();
