import { describe, it, expect } from 'vitest'
import {
  computeTrustScore,
  createFreshRecord,
  formatPluginTrustBadge,
  mergeInstallResult,
} from '../pluginTrust.js'

describe('computeTrustScore', () => {
  it('returns null for a record with no observations', () => {
    expect(computeTrustScore(createFreshRecord('x'))).toBeNull()
  })

  it('returns 1.0 for all-success', () => {
    const r = mergeInstallResult(createFreshRecord('x'), true, 0)
    const r2 = mergeInstallResult(r, true, 0)
    expect(computeTrustScore(r2)).toBe(1)
  })

  it('returns 0 for all-failure', () => {
    const r = mergeInstallResult(createFreshRecord('x'), false, 0)
    expect(computeTrustScore(r)).toBe(0)
  })

  it('returns the success ratio otherwise', () => {
    let r = createFreshRecord('x')
    for (let i = 0; i < 9; i++) r = mergeInstallResult(r, true, i)
    r = mergeInstallResult(r, false, 10)
    const score = computeTrustScore(r)
    expect(score).toBeCloseTo(0.9, 3)
  })
})

describe('mergeInstallResult', () => {
  it('increments installs for success', () => {
    const r = mergeInstallResult(createFreshRecord('x'), true, 100)
    expect(r.installs).toBe(1)
    expect(r.failures).toBe(0)
    expect(r.lastUpdated).toBe(100)
  })

  it('increments failures for failure', () => {
    const r = mergeInstallResult(createFreshRecord('x'), false, 200)
    expect(r.installs).toBe(0)
    expect(r.failures).toBe(1)
    expect(r.lastUpdated).toBe(200)
  })

  it('preserves firstSeen across observations', () => {
    const r1 = mergeInstallResult(createFreshRecord('x', 100), true, 200)
    const r2 = mergeInstallResult(r1, false, 300)
    expect(r2.firstSeen).toBe(100)
  })

  it('does not mutate the input record', () => {
    const input = createFreshRecord('x')
    const out = mergeInstallResult(input, true, 0)
    expect(input.installs).toBe(0)
    expect(out).not.toBe(input)
  })
})

describe('formatPluginTrustBadge', () => {
  it('renders "new" when there are no observations', () => {
    const badge = formatPluginTrustBadge(createFreshRecord('x'))
    expect(badge).toMatch(/new/i)
  })

  it('renders score and ratio for healthy plugins', () => {
    let r = createFreshRecord('x')
    for (let i = 0; i < 10; i++) r = mergeInstallResult(r, true, i)
    const badge = formatPluginTrustBadge(r)
    expect(badge).toContain('100%')
    expect(badge).toContain('10/10')
  })

  it('flags problematic plugins visibly', () => {
    let r = createFreshRecord('x')
    r = mergeInstallResult(r, true, 0)
    r = mergeInstallResult(r, false, 1)
    r = mergeInstallResult(r, false, 2)
    const badge = formatPluginTrustBadge(r)
    expect(badge).toMatch(/33%|34%/) // 1/3
    // Should include some visual signal that this is below a sensible threshold
    expect(badge).toMatch(/\u26a0|warn|problem|below/i)
  })
})
