import type { AdminPlayTypeRow } from "@/types/api/admin-config";

export type OddsCategoryTab = "all" | "d4" | "d3" | "d2";

export type OddsPlayFilterGroupKey = "bigSmall" | "combo4" | "number3" | "number2" | "other";

type GroupDef = {
  key: OddsPlayFilterGroupKey;
  match: (row: AdminPlayTypeRow) => boolean;
};

const ODDS_PLAY_FILTER_GROUPS: GroupDef[] = [
  {
    key: "bigSmall",
    match: (row) => row.play_code === "big" || row.play_code === "small",
  },
  {
    key: "combo4",
    match: (row) => row.category === "position" && row.dimension === 4,
  },
  {
    key: "number3",
    match: (row) => row.category === "position" && row.dimension === 3,
  },
  {
    key: "number2",
    match: (row) => row.category === "position" && row.dimension === 2,
  },
  {
    key: "other",
    match: (row) =>
      row.category === "box"
      || row.category === "attribute"
      || (row.category === "standard" && row.play_code !== "big" && row.play_code !== "small"),
  },
];

export function filterOddsPlayTypesByCategory(
  tab: OddsCategoryTab,
  types: AdminPlayTypeRow[],
): AdminPlayTypeRow[] {
  if (tab === "all") {
    return types;
  }
  const dim = tab === "d4" ? 4 : tab === "d3" ? 3 : 2;
  return types.filter((t) => t.dimension === dim);
}

export function buildOddsPlayFilterGroups(
  tab: OddsCategoryTab,
  types: AdminPlayTypeRow[],
): { key: OddsPlayFilterGroupKey; types: AdminPlayTypeRow[] }[] {
  const filtered = filterOddsPlayTypesByCategory(tab, types);
  return ODDS_PLAY_FILTER_GROUPS.map((def) => ({
    key: def.key,
    types: filtered
      .filter(def.match)
      .sort((a, b) => a.sort_order - b.sort_order || a.play_code.localeCompare(b.play_code)),
  })).filter((group) => group.types.length > 0);
}
