/**
 * Report controller
 * - Generates daily/weekly/monthly reports
 */

const { getBaseStats } = require('../models/report.model');

function toYMD(date) {
  // Returns YYYY-MM-DD suitable for MySQL DATE comparisons
  return date.toISOString().slice(0, 10);
}

function startOfDay(d) {
  const x = new Date(d);
  x.setHours(0, 0, 0, 0);
  return x;
}

function addDays(d, days) {
  const x = new Date(d);
  x.setDate(x.getDate() + days);
  return x;
}

async function daily(req, res) {
  const { date } = req.params; // YYYY-MM-DD
  const from = startOfDay(date);
  const to = addDays(from, 1); // exclusive

  const stats = await getBaseStats({
    dateFrom: toYMD(from),
    dateTo: toYMD(addDays(from, 0))
  });

  return res.json({ type: 'daily', date, ...stats });
}

async function weekly(req, res) {
  const { weekStart } = req.params; // YYYY-MM-DD
  const from = startOfDay(weekStart);
  const toDate = addDays(from, 6);

  const stats = await getBaseStats({
    dateFrom: toYMD(from),
    dateTo: toYMD(toDate)
  });

  return res.json({ type: 'weekly', weekStart, weekEnd: toYMD(toDate), ...stats });
}

async function monthly(req, res) {
  const { year, month } = req.params; // month: 01..12
  const from = new Date(Number(year), Number(month) - 1, 1);
  const toDate = new Date(Number(year), Number(month), 0); // last day of month

  const stats = await getBaseStats({
    dateFrom: toYMD(from),
    dateTo: toYMD(toDate)
  });

  return res.json({ type: 'monthly', year: Number(year), month: Number(month), ...stats });
}

module.exports = { daily, weekly, monthly };

