const moment = require('moment');

class DateUtils {
  /**
   * Calculate date ranges for time period queries
   */
  static calculateDateRange(period, count = 6) {
    const now = moment();
    let startDate, endDate;

    switch (period) {
      case 'months':
        startDate = now.subtract(count, 'months').startOf('month');
        endDate = now.endOf('month');
        break;
      case 'weeks':
        startDate = now.subtract(count, 'weeks').startOf('week');
        endDate = now.endOf('week');
        break;
      case 'years':
        startDate = now.subtract(count, 'years').startOf('year');
        endDate = now.endOf('year');
        break;
      default:
        startDate = now.subtract(6, 'months').startOf('month');
        endDate = now.endOf('month');
    }

    return {
      start: startDate.format('YYYY-MM-DD'),
      end: endDate.format('YYYY-MM-DD')
    };
  }

  /**
   * Format date for SQL queries
   */
  static formatForSQL(dateString) {
    return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
  }

  /**
   * Format date for display
   */
  static formatForDisplay(dateString) {
    return moment(dateString).format('MMM DD, YYYY');
  }

  /**
   * Get current date range for queries
   */
  static getCurrentDateRange() {
    const now = moment();
    return {
      start: now.subtract(6, 'months').format('YYYY-MM-DD'),
      end: now.format('YYYY-MM-DD')
    };
  }

  /**
   * Group dates by month/week/year
   */
  static groupByPeriod(dateString, period = 'month') {
    const date = moment(dateString);
    
    switch (period) {
      case 'month':
        return date.format('YYYY-MM');
      case 'week':
        return `${date.format('YYYY')}-W${date.week()}`;
      case 'year':
        return date.format('YYYY');
      default:
        return date.format('YYYY-MM');
    }
  }
}

module.exports = DateUtils;

