export function billingPeriod(billingDay: number, date: Date) {
  // Determine the anchor month and year
  let anchorMonth, anchorYear

  if (date.getDate() >= billingDay) {
    anchorMonth = date.getMonth() + 1 // JavaScript months are 0-11
    anchorYear = date.getFullYear()
  } else {
    // Move to previous month
    if (date.getMonth() === 0) {
      // January
      anchorMonth = 12
      anchorYear = date.getFullYear() - 1
    } else {
      anchorMonth = date.getMonth() // No +1 because we're going backwards
      anchorYear = date.getFullYear()
    }
  }

  // Calculate start date
  const lastDayOfMonth = new Date(anchorYear, anchorMonth, 0).getDate()
  const startDay = Math.min(billingDay, lastDayOfMonth)
  const startDate = new Date(anchorYear, anchorMonth - 1, startDay) // -1 because JS months are 0-based

  // Calculate next month and year
  let nextMonth, nextYear
  if (anchorMonth === 12) {
    nextMonth = 1
    nextYear = anchorYear + 1
  } else {
    nextMonth = anchorMonth + 1
    nextYear = anchorYear
  }

  // Calculate end date
  const nextLastDayOfMonth = new Date(nextYear, nextMonth, 0).getDate()
  const endDay = Math.min(billingDay, nextLastDayOfMonth)
  const endDate = new Date(nextYear, nextMonth - 1, endDay)
  endDate.setDate(endDate.getDate() - 1) // Subtract one day

  return [startDate, endDate]
}

export function formatDate(date = new Date()) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // e.g: January = 01
  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}
