export type ReportPeriodKey = 'thisMonth' | 'lastMonth' | 'custom'

export type ReportPeriodRange = {
    from: string
    to: string
}

/** Formats a Date as an ISO "YYYY-MM-DD" string (local time, no timezone shift). */
function toIsoDate(date: Date): string {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

/** Returns the {from, to} range (inclusive) for a given month offset relative to now. */
function getMonthRange(offset: number): ReportPeriodRange {
    const now = new Date()
    const start = new Date(now.getFullYear(), now.getMonth() + offset, 1)
    const end = new Date(now.getFullYear(), now.getMonth() + offset + 1, 0)
    return { from: toIsoDate(start), to: toIsoDate(end) }
}

export function useReportingFilters() {
    const thisMonth = (): ReportPeriodRange => getMonthRange(0)
    const lastMonth = (): ReportPeriodRange => getMonthRange(-1)

    /** Resolves a preset key to a concrete range. `custom` keeps the provided range. */
    function rangeForPreset(key: ReportPeriodKey, current: ReportPeriodRange): ReportPeriodRange {
        switch (key) {
            case 'thisMonth':
                return thisMonth()
            case 'lastMonth':
                return lastMonth()
            case 'custom':
                return current
        }
    }

    return { thisMonth, lastMonth, rangeForPreset, toIsoDate }
}
