import { describe, expect, it } from "vitest";
import {
  getSplitTotal,
  hasExactSplitTotal,
  normalizeTeamMember,
  validateEmployeeTeamMembers
} from "./shop-employee-teams.form.utils.js";

describe("shop employee team form utilities", () => {
  it("normalizes missing payout defaults for a team member", () => {
    expect(
      normalizeTeamMember({
        employeeid: "emp-1",
        percentage: 100
      })
    ).toEqual({
      employeeid: "emp-1",
      percentage: 100,
      payout_method: "hourly",
      labor_rates: {},
      commission_rates: {}
    });
  });

  it("returns a minimum-member validation error when no team members are provided", () => {
    expect(validateEmployeeTeamMembers([])).toEqual({
      normalizedTeamMembers: [],
      errorKey: "employee_teams.errors.minimum_one_member"
    });
  });

  it("rejects duplicate employees in the same team", () => {
    const result = validateEmployeeTeamMembers([
      { employeeid: "emp-1", percentage: 50, labor_rates: { LAA: 25 } },
      { employeeid: "emp-1", percentage: 50, labor_rates: { LAA: 30 } }
    ]);

    expect(result.errorKey).toBe("employee_teams.errors.duplicate_member");
  });

  it("rejects team allocations that do not add up to exactly one hundred percent", () => {
    const result = validateEmployeeTeamMembers([
      { employeeid: "emp-1", percentage: 60, labor_rates: { LAA: 25 } },
      { employeeid: "emp-2", percentage: 30, labor_rates: { LAA: 30 } }
    ]);

    expect(getSplitTotal(result.normalizedTeamMembers)).toBe(90);
    expect(hasExactSplitTotal(result.normalizedTeamMembers)).toBe(false);
    expect(result.errorKey).toBe("employee_teams.errors.allocation_total_exact");
  });

  it("accepts a valid mixed hourly and commission team and strips graph metadata", () => {
    const result = validateEmployeeTeamMembers([
      {
        __typename: "employee_team_members",
        employeeid: "emp-1",
        percentage: 40,
        labor_rates: { LAA: 28.5 }
      },
      {
        employeeid: "emp-2",
        percentage: 60,
        payout_method: "commission",
        commission_rates: { LAA: 35 }
      }
    ]);

    expect(result.errorKey).toBeNull();
    expect(result.normalizedTeamMembers).toEqual([
      {
        employeeid: "emp-1",
        percentage: 40,
        payout_method: "hourly",
        labor_rates: { LAA: 28.5 },
        commission_rates: {}
      },
      {
        employeeid: "emp-2",
        percentage: 60,
        payout_method: "commission",
        labor_rates: {},
        commission_rates: { LAA: 35 }
      }
    ]);
  });
});
