import { describe, it, expect } from 'vitest'
import {
  WORKSTREAM_TYPE_OPTIONS,
  isValidWorkstreamType,
  reorder,
  type Workstream,
} from '@/lib/pmo/workstreams'

describe('WORKSTREAM_TYPE_OPTIONS', () => {
  it('contains the 3 canonical types in PLT-Playbook order', () => {
    expect(WORKSTREAM_TYPE_OPTIONS.map((t) => t.value)).toEqual([
      'taskforce',
      'core',
      'support',
    ])
  })
})

describe('isValidWorkstreamType', () => {
  it('accepts the 3 canonical types', () => {
    expect(isValidWorkstreamType('taskforce')).toBe(true)
    expect(isValidWorkstreamType('core')).toBe(true)
    expect(isValidWorkstreamType('support')).toBe(true)
  })
  it('rejects others', () => {
    expect(isValidWorkstreamType('extension')).toBe(false)
    expect(isValidWorkstreamType('')).toBe(false)
    expect(isValidWorkstreamType(null)).toBe(false)
  })
})

describe('reorder', () => {
  function mk(id: string, sort_order: number): Workstream {
    return { id, type: 'core', name: id, sort_order, owner_member_id: null }
  }

  it('moves an item from one position to another and re-sequences sort_order from 0', () => {
    const result = reorder(
      [mk('a', 0), mk('b', 10), mk('c', 20), mk('d', 30)],
      'c',
      0,
    )
    expect(result.map((w) => w.id)).toEqual(['c', 'a', 'b', 'd'])
    expect(result.map((w) => w.sort_order)).toEqual([0, 1, 2, 3])
  })

  it('no-op when moving to its current position', () => {
    const items = [mk('a', 0), mk('b', 10)]
    const result = reorder(items, 'a', 0)
    expect(result.map((w) => w.id)).toEqual(['a', 'b'])
  })

  it('returns the input unchanged when id is not present', () => {
    const items = [mk('a', 0), mk('b', 10)]
    const result = reorder(items, 'missing', 0)
    expect(result.map((w) => w.id)).toEqual(['a', 'b'])
  })

  it('clamps toIndex into the valid range', () => {
    const items = [mk('a', 0), mk('b', 10), mk('c', 20)]
    const result = reorder(items, 'a', 99)
    expect(result.map((w) => w.id)).toEqual(['b', 'c', 'a'])
  })
})
