// tests/check-dist-wc-freshness.test.ts
//
// INFRA-F84 残余② 的提示脚本。它**不是**闸（永不非零退出），所以这里钉的是
// 「三种状态判对 + 文案真的说出该做什么」，而不是 exit code。
import { describe, it, expect } from 'vitest'
import { mkdtempSync, mkdirSync, writeFileSync, utimesSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
  judge,
  describe as describeVerdict,
  newestMtime,
} from '../scripts/check-dist-wc-freshness.mjs'

describe('judge', () => {
  it('reports missing when dist-wc has never been built', () => {
    expect(judge(1_000_000, null)).toEqual({ state: 'missing', behindMs: 0 })
  })

  it('reports stale when src is newer than the built output', () => {
    const v = judge(1_000_000 + 60_000, 1_000_000)
    expect(v.state).toBe('stale')
    expect(v.behindMs).toBe(60_000)
  })

  it('does NOT report stale for a sub-second difference (build:wc reads src while writing dist-wc)', () => {
    expect(judge(1_000_500, 1_000_000).state).toBe('fresh')
  })

  it('reports fresh when the output is newer', () => {
    expect(judge(1_000_000, 2_000_000).state).toBe('fresh')
  })

  it('reports fresh when there is no src at all (nothing to be behind)', () => {
    expect(judge(null, 1_000_000).state).toBe('fresh')
  })
})

describe('describe', () => {
  it('tells you the exact command in the stale message (a warning nobody can act on is noise)', () => {
    const msg = describeVerdict({ state: 'stale', behindMs: 120_000 })
    expect(msg).toMatch(/pnpm build:wc/)
    expect(msg).toMatch(/React tab/)
    expect(msg).toMatch(/2 分钟/)
  })

  it('states the mtime caveat so nobody reads it as a guarantee', () => {
    expect(describeVerdict({ state: 'stale', behindMs: 1 })).toMatch(/mtime/)
  })

  it('names the command for the missing case too', () => {
    expect(describeVerdict({ state: 'missing', behindMs: 0 })).toMatch(/pnpm build:wc/)
  })

  it('still prints something when fresh (silence cannot be told apart from a broken script)', () => {
    expect(describeVerdict({ state: 'fresh', behindMs: 0 })).toMatch(/dist-wc/)
  })
})

describe('newestMtime', () => {
  it('returns null for a directory that does not exist', () => {
    expect(newestMtime(join(tmpdir(), 'definitely-not-here-' + Date.now()))).toBeNull()
  })

  it('walks nested directories and returns the newest timestamp', () => {
    const root = mkdtempSync(join(tmpdir(), 'wc-fresh-'))
    mkdirSync(join(root, 'nested'), { recursive: true })
    writeFileSync(join(root, 'old.txt'), 'a')
    writeFileSync(join(root, 'nested', 'new.txt'), 'b')
    const oldTime = new Date(2000, 0, 1)
    const newTime = new Date(2020, 0, 1)
    utimesSync(join(root, 'old.txt'), oldTime, oldTime)
    utimesSync(join(root, 'nested', 'new.txt'), newTime, newTime)
    expect(newestMtime(root)).toBe(newTime.getTime())
  })
})
