import { describe, it, expect } from 'vitest'
import { shouldAutoCheckYtdlp, AUTO_UPDATE_INTERVAL_MS } from '../src/main/core/ytdlpPolicy'

const NOW = 1_782_435_469_486 // arbitrary fixed "now"

describe('shouldAutoCheckYtdlp', () => {
  it('never checks when auto-update is disabled', () => {
    expect(shouldAutoCheckYtdlp(false, 0, NOW)).toBe(false)
    // …even if a full interval has elapsed.
    expect(shouldAutoCheckYtdlp(false, NOW - AUTO_UPDATE_INTERVAL_MS * 2, NOW)).toBe(false)
  })

  it('checks on first run (lastCheck is 0 / never)', () => {
    expect(shouldAutoCheckYtdlp(true, 0, NOW)).toBe(true)
  })

  it('skips while inside the throttle window', () => {
    // Checked one minute ago → far inside the 24h window.
    expect(shouldAutoCheckYtdlp(true, NOW - 60_000, NOW)).toBe(false)
    // Exactly one ms short of the interval still skips.
    expect(shouldAutoCheckYtdlp(true, NOW - (AUTO_UPDATE_INTERVAL_MS - 1), NOW)).toBe(false)
  })

  it('checks once the interval has elapsed (boundary inclusive)', () => {
    expect(shouldAutoCheckYtdlp(true, NOW - AUTO_UPDATE_INTERVAL_MS, NOW)).toBe(true)
    expect(shouldAutoCheckYtdlp(true, NOW - AUTO_UPDATE_INTERVAL_MS * 3, NOW)).toBe(true)
  })

  it('honours a custom interval', () => {
    const hour = 60 * 60 * 1000
    expect(shouldAutoCheckYtdlp(true, NOW - 30 * 60_000, NOW, hour)).toBe(false)
    expect(shouldAutoCheckYtdlp(true, NOW - hour, NOW, hour)).toBe(true)
  })

  it('checks when the clock ran backward (lastCheck is in the future, R9)', () => {
    // A backward clock correction leaves lastCheck > now → (now - lastCheck) is
    // negative; without the guard the check would be skipped forever.
    expect(shouldAutoCheckYtdlp(true, NOW + AUTO_UPDATE_INTERVAL_MS, NOW)).toBe(true)
    expect(shouldAutoCheckYtdlp(true, NOW + 1, NOW)).toBe(true)
  })
})
