// Pure helpers for pmo_workstreams. UI in components/pmo/.

export type WorkstreamType = 'taskforce' | 'core' | 'support'

export interface WorkstreamTypeOption {
  value: WorkstreamType
  label: string
  description: string
}

/** Order mirrors the PLT-Playbook (Slide 7): TASKFORCE first, then CORE, then SUPPORT. */
export const WORKSTREAM_TYPE_OPTIONS: ReadonlyArray<WorkstreamTypeOption> = [
  {
    value: 'taskforce',
    label: 'TASKFORCE',
    description: 'Konzeptionelle Verbesserungen, Wochenziele, Tagesaktivitäten je Arbeitspaket',
  },
  {
    value: 'core',
    label: 'CORE',
    description: 'Operativ, OEE-getrieben — Mo Priorisierung → Fr Lösung',
  },
  {
    value: 'support',
    label: 'SUPPORT & EXTENSION',
    description: 'Ersatzteile, Material, Hochlauf neuer Linien',
  },
]

const WORKSTREAM_TYPE_VALUES = new Set(WORKSTREAM_TYPE_OPTIONS.map((t) => t.value))

export function isValidWorkstreamType(v: unknown): v is WorkstreamType {
  return typeof v === 'string' && WORKSTREAM_TYPE_VALUES.has(v as WorkstreamType)
}

export interface Workstream {
  id: string
  type: WorkstreamType
  name: string
  sort_order: number
  owner_member_id: string | null
}

/**
 * Move a workstream by id from its current position to `toIndex`. Returns a new
 * list with `sort_order` re-sequenced to 0, 1, 2, ... so the caller can persist
 * the new ordering with one batched UPDATE per row.
 *
 * No-ops if the id is missing. Clamps `toIndex` into [0, list.length - 1].
 */
export function reorder<T extends Workstream>(list: T[], id: string, toIndex: number): T[] {
  const fromIndex = list.findIndex((w) => w.id === id)
  if (fromIndex === -1) return list

  const clamped = Math.min(Math.max(toIndex, 0), list.length - 1)
  if (clamped === fromIndex) {
    return list.map((w, i) => ({ ...w, sort_order: i }))
  }

  const next = [...list]
  const [moved] = next.splice(fromIndex, 1)
  next.splice(clamped, 0, moved)
  return next.map((w, i) => ({ ...w, sort_order: i }))
}
