import type { SolveInput, ShiftAssignment } from '~/shared/types/schedule'
import { getDaysInRange } from '~/app/utils/dateHelpers'

export function parseAssignments(result: Record<string, unknown>, input: SolveInput): ShiftAssignment[] {
  const { employees, framework, period_start, period_end } = input
  const days = getDaysInRange(period_start, period_end)
  const E = employees.length
  const S = framework.shifts.length
  const D = days.length
  const assignments: ShiftAssignment[] = []

  const solution = result.Columns as Record<string, { Primal: number }>

  for (let e = 0; e < E; e++) {
    for (let s = 0; s < S; s++) {
      for (let d = 0; d < D; d++) {
        const varName = `x_${e}_${s}_${d}`
        const value = solution[varName]?.Primal ?? 0
        if (value > 0.5) {
          const shift = framework.shifts[s]
          const period = framework.periods.find(p => p.id === shift.period_id)
          assignments.push({
            employee_id: employees[e].id,
            employee_name: employees[e].name,
            shift_id: shift.id,
            shift_name: shift.name,
            period_id: shift.period_id,
            date: days[d],
            start_time: period?.start_time ?? '00:00',
            end_time: period?.end_time ?? '00:00',
          })
        }
      }
    }
  }

  return assignments
}
