import { type CreateOrUpdateShiftRotationVC } from 'src/services/shifts';

import { type ShiftRotationFormData } from '../../../form';

/**
 * Maps the rotation form state to the create/update payload expected by the
 * backend. Each shift inside a day is embedded inline (the API does not
 * reference templates from the shift repository).
 */
export const parseRotationPayload = (
  data: ShiftRotationFormData,
): CreateOrUpdateShiftRotationVC => ({
  name: data.name.trim(),
  description: data.description?.trim() || undefined,
  days: data.days.map(day => ({
    type: day.type === 'shift' ? 'WORK' : 'REST',
    shifts:
      day.type === 'shift'
        ? (day.shifts ?? []).map(shift => ({
            ...(shift.shiftCode && { shiftCode: shift.shiftCode }),
            name: shift.name,
            color: shift.color ?? undefined,
            description: shift.description?.trim() || undefined,
            timeSlots: shift.timeSlots.map(
              slot => [slot.startTime, slot.endTime] as [string, string],
            ),
          }))
        : [],
  })),
});
