export const LABOR_TYPES = [
  "LAA",
  "LAB",
  "LAD",
  "LAE",
  "LAF",
  "LAG",
  "LAM",
  "LAR",
  "LAS",
  "LAU",
  "LA1",
  "LA2",
  "LA3",
  "LA4"
];

export const normalizeTeamMember = (teamMember = {}) => ({
  ...teamMember,
  payout_method: teamMember.payout_method || "hourly",
  labor_rates: teamMember.labor_rates || {},
  commission_rates: teamMember.commission_rates || {}
});

export const normalizeEmployeeTeam = (employeeTeam = {}) => ({
  ...employeeTeam,
  employee_team_members: (employeeTeam.employee_team_members || []).map(normalizeTeamMember)
});

export const getSplitTotal = (teamMembers = []) =>
  teamMembers.reduce((sum, member) => sum + Number(member?.percentage || 0), 0);

export const hasExactSplitTotal = (teamMembers = []) => Math.abs(getSplitTotal(teamMembers) - 100) < 0.00001;

export const validateEmployeeTeamMembers = (employeeTeamMembers = []) => {
  const normalizedTeamMembers = employeeTeamMembers.map((teamMember) => {
    const nextTeamMember = normalizeTeamMember({ ...teamMember });
    delete nextTeamMember.__typename;
    return nextTeamMember;
  });

  if (normalizedTeamMembers.length === 0) {
    return {
      normalizedTeamMembers,
      errorKey: "employee_teams.errors.minimum_one_member"
    };
  }

  const employeeIds = normalizedTeamMembers.map((teamMember) => teamMember.employeeid).filter(Boolean);
  const duplicateEmployeeIds = employeeIds.filter((employeeId, index) => employeeIds.indexOf(employeeId) !== index);

  if (duplicateEmployeeIds.length > 0) {
    return {
      normalizedTeamMembers,
      errorKey: "employee_teams.errors.duplicate_member"
    };
  }

  if (!hasExactSplitTotal(normalizedTeamMembers)) {
    return {
      normalizedTeamMembers,
      errorKey: "employee_teams.errors.allocation_total_exact"
    };
  }

  return {
    normalizedTeamMembers,
    errorKey: null
  };
};
