package com.applemand.zmanim.core.datetime

import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import kotlinx.datetime.minus
import kotlinx.datetime.plus

object DateRanges {
    fun week(anchor: LocalDate, weekStart: DayOfWeek = DayOfWeek.SUNDAY): List<LocalDate> {
        val delta = (anchor.dayOfWeek.isoDayNumber - weekStart.isoDayNumber + 7) % 7
        val start = anchor.minus(delta, DateTimeUnit.DAY)
        return (0 until 7).map { start.plus(it, DateTimeUnit.DAY) }
    }

    /** 6×7 calendar grid rows, Sunday-first by default. */
    fun monthGrid(year: Int, month: Int, weekStart: DayOfWeek = DayOfWeek.SUNDAY): List<LocalDate> {
        val first = LocalDate(year, month, 1)
        val lead = (first.dayOfWeek.isoDayNumber - weekStart.isoDayNumber + 7) % 7
        val start = first.minus(lead, DateTimeUnit.DAY)
        return (0 until 42).map { start.plus(it, DateTimeUnit.DAY) }
    }

    fun daysUntil(from: LocalDate, to: LocalDate): Int =
        from.toEpochDays().let { to.toEpochDays() - it }
}

private val DayOfWeek.isoDayNumber: Int
    get() = ordinal + 1
