import type { StatusTone } from "@/components/ui/status-badge"

export type WorkflowStep = {
  status: string
  label: { en: string; ar: string }
  tone: StatusTone
}

export type WorkflowAction = {
  key: string
  label: { en: string; ar: string }
  variant?: "primary" | "outline" | "danger" | "secondary"
  icon?: string
  requireReason?: boolean
  requireConfirmation?: boolean
  danger?: boolean
}

export type WorkflowDefinition = {
  steps: WorkflowStep[]
  actions: Record<string, WorkflowAction[]>
  stepIndex: (status: string) => number
}

export function makeStepIndex(steps: WorkflowStep[]) {
  return (status: string) => steps.findIndex(s => s.status === status || s.status === normalizeStatus(status))
}

export function normalizeStatus(status: string): string {
  return status.toLowerCase().replace(/[\s-]+/g, "_")
}

export function getCurrentStep(def: WorkflowDefinition, status: string): number {
  return def.stepIndex(status)
}

export function getAllowedActions(def: WorkflowDefinition, status: string, permissions: string[] = [], permissionMap?: Record<string, string>): WorkflowAction[] {
  const norm = normalizeStatus(status)
  const actions = def.actions[norm] ?? def.actions[status] ?? []
  if (!permissionMap) return actions
  const granted = new Set(permissions)
  if (granted.has("*")) return actions
  return actions.filter(action => {
    const perm = permissionMap[action.key]
    if (!perm) return true
    return granted.has(perm)
  })
}

export function getStepTone(def: WorkflowDefinition, status: string, currentIndex: number): StatusTone {
  const stepIdx = def.stepIndex(status)
  if (stepIdx < 0) return "neutral"
  if (stepIdx < currentIndex) return "success"
  if (stepIdx === currentIndex) return "processing"
  return "neutral"
}
