import { describe, it, expect } from 'vitest'
import {
  getLocalDateKey,
  addToDailySpend,
  getTodaySpend,
  pruneOldDays,
} from '../utils/dailySpend.js'

describe('getLocalDateKey', () => {
  it('returns YYYY-MM-DD in local time', () => {
    // 2026-04-17 at 10:00 local → 2026-04-17
    const d = new Date(2026, 3, 17, 10, 0, 0) // month is 0-indexed
    expect(getLocalDateKey(d)).toBe('2026-04-17')
  })

  it('pads month and day to two digits', () => {
    const d = new Date(2026, 0, 5, 0, 0, 0) // Jan 5
    expect(getLocalDateKey(d)).toBe('2026-01-05')
  })
})

describe('addToDailySpend', () => {
  it('creates a bucket for a new date', () => {
    const store = addToDailySpend({}, new Date(2026, 3, 17), 1.25)
    expect(store).toEqual({ '2026-04-17': 1.25 })
  })

  it('accumulates into an existing bucket', () => {
    const store = addToDailySpend({ '2026-04-17': 1.0 }, new Date(2026, 3, 17), 0.5)
    expect(store).toEqual({ '2026-04-17': 1.5 })
  })

  it('does not mutate the input store', () => {
    const input = { '2026-04-17': 1.0 }
    const out = addToDailySpend(input, new Date(2026, 3, 17), 0.5)
    expect(input).toEqual({ '2026-04-17': 1.0 })
    expect(out).not.toBe(input)
  })

  it('ignores zero or negative amounts', () => {
    expect(addToDailySpend({}, new Date(), 0)).toEqual({})
    expect(addToDailySpend({}, new Date(), -5)).toEqual({})
  })
})

describe('getTodaySpend', () => {
  it('returns 0 when no spend is recorded', () => {
    expect(getTodaySpend({}, new Date(2026, 3, 17))).toBe(0)
    expect(getTodaySpend({ '2026-04-16': 5 }, new Date(2026, 3, 17))).toBe(0)
  })

  it('returns today bucket when present', () => {
    expect(getTodaySpend({ '2026-04-16': 5, '2026-04-17': 2.5 }, new Date(2026, 3, 17))).toBe(2.5)
  })
})

describe('pruneOldDays', () => {
  it('keeps the most recent N days (today + N-1 previous)', () => {
    const store = {
      '2026-04-01': 1, // 16 days ago — drop
      '2026-04-10': 2, // 7 days ago — drop (boundary: >7 outside window)
      '2026-04-11': 3, // 6 days ago — keep
      '2026-04-15': 4,
      '2026-04-17': 5,
    }
    const pruned = pruneOldDays(store, new Date(2026, 3, 17), 7)
    expect(Object.keys(pruned).sort()).toEqual(['2026-04-11', '2026-04-15', '2026-04-17'])
  })

  it('does not drop today', () => {
    const store = { '2026-04-17': 1 }
    const pruned = pruneOldDays(store, new Date(2026, 3, 17), 1)
    expect(pruned).toEqual({ '2026-04-17': 1 })
  })

  it('returns a new object without mutating', () => {
    const input = { '2026-01-01': 1 }
    const out = pruneOldDays(input, new Date(2026, 3, 17), 7)
    expect(input).toEqual({ '2026-01-01': 1 })
    expect(out).not.toBe(input)
  })
})
