import { RewardSelectionItem } from '@isa/checkout/data-access';
import { formatAddress } from './format-address.helper';

export type SubGroup = {
  branchId?: number;
  branchName?: string;
  branchAddress?: string;
  items: RewardSelectionItem[];
};

const ORDER_TYPES_WITH_BRANCH_GROUPING = ['Abholung', 'Rücklage'] as const;

const sortByProductName = (items: RewardSelectionItem[]): RewardSelectionItem[] => {
  return [...items].sort((a, b) =>
    (a.item.product.name ?? '').localeCompare(b.item.product.name ?? ''),
  );
};

export const groupByBranch = (
  orderType: string,
  items: RewardSelectionItem[],
): SubGroup[] => {
  const needsBranchGrouping = ORDER_TYPES_WITH_BRANCH_GROUPING.includes(
    orderType as (typeof ORDER_TYPES_WITH_BRANCH_GROUPING)[number],
  );

  if (!needsBranchGrouping) {
    return [
      {
        branchId: undefined,
        branchName: undefined,
        branchAddress: undefined,
        items: sortByProductName(items),
      },
    ];
  }

  const branchGroups = items.reduce((map, item) => {
    const branchId = item.item.destination?.data?.targetBranch?.id ?? 0;
    if (!map.has(branchId)) map.set(branchId, []);
    map.get(branchId)!.push(item);
    return map;
  }, new Map<number, RewardSelectionItem[]>());

  return Array.from(branchGroups.entries())
    .sort(([a], [b]) => a - b)
    .map(([branchId, branchItems]) => {
      const branch = branchItems[0]?.item.destination?.data?.targetBranch?.data;
      return {
        branchId: branchId || undefined,
        branchName: branch?.name,
        branchAddress: formatAddress(branch?.address),
        items: sortByProductName(branchItems),
      };
    });
};
