import type { GridValidRowModel } from "@mui/x-data-grid";

import type { DataTableColDef } from "./data-table-types";

/** DataGrid falls back to this when a column sets no width. */
const DEFAULT_COLUMN_WIDTH = 100;

/**
 * How wide the table is with every column at its set width.
 *
 * Use this instead of writing the number by hand: a hand-written value stops
 * matching as soon as a column width changes, and the difference shows up as
 * empty space after the last column.
 */
export function getColumnsTotalWidth<Row extends GridValidRowModel>(
  columns: DataTableColDef<Row>[],
  columnVisibility: Record<string, boolean> = {},
): number {
  return columns.reduce((total, column) => {
    if (columnVisibility[column.field] === false) return total;

    const width =
      typeof column.width === "number" ? column.width : DEFAULT_COLUMN_WIDTH;

    return total + width;
  }, 0);
}
