import { Match } from "@/features/matches/types";
import { BracketData } from "../types";

export const groupMatchesIntoBracket = (matches?: Match[]): BracketData => {
  if (!matches || matches.length === 0) {
    return { winners: [], losers: [] };
  }

  const winnersMap = new Map<number, Match[]>();
  const losersMap = new Map<number, Match[]>();

  matches
    .filter((match) => match.round !== -1)
    .sort((a, b) => a.lid - b.lid)
    .forEach((match) => {
      if (!match.is_losers_bracket) {
        if (!winnersMap.has(match.round)) {
          winnersMap.set(match.round, []);
        }
        winnersMap.get(match.round)!.push(match);
      } else {
        if (!losersMap.has(match.round)) {
          losersMap.set(match.round, []);
        }
        losersMap.get(match.round)!.push(match);
      }
    });

  const winners = Array.from(winnersMap.entries())
    .sort(([a], [b]) => a - b)
    .map(([, matches]) => matches);

  const losers = Array.from(losersMap.entries())
    .sort(([a], [b]) => a - b)
    .map(([, matches]) => matches);
  return { winners, losers };
};
