import { type ShiftManagementFilteredProperties } from 'src/types/amplitude';
import { type SegmentationGroup } from 'src/types/timeTracking';

/**
 * Builds the groups array from drawer segmentation state (segment checkboxes).
 * Only includes groups that have at least one selected item.
 */
function buildSegmentsGroups(
  segmentationItems: Record<string, boolean>,
  segmentationGroups: SegmentationGroup[],
): ShiftManagementFilteredProperties['segmentsFilters']['groups'] {
  const groups: { name: string; elements: string[] }[] = [];

  for (const group of segmentationGroups) {
    const elements = group.items
      .filter(item => segmentationItems[String(item.value)] === true)
      .map(item => item.label);
    if (elements.length > 0) {
      groups.push({ name: group.name, elements });
    }
  }

  return groups;
}

/**
 * Builds the full payload for SHIFT_MANAGEMENT_FILTERED.
 * totalCollaborators = count of collaborators selected in the drawer's user multi-dropdown.
 */
export function buildShiftManagementFilteredPayload(
  siteFilters: boolean,
  segmentationItems: Record<string, boolean>,
  segmentationGroups: SegmentationGroup[],
  selectedCollaboratorsCount: number,
): ShiftManagementFilteredProperties {
  return {
    siteFilters,
    segmentsFilters: {
      totalCollaborators: selectedCollaboratorsCount,
      groups: buildSegmentsGroups(segmentationItems, segmentationGroups),
    },
  };
}
