import type { SortingState } from '@tanstack/angular-table';
import { toSequelizeOrderEntry } from './nested-column';

/**
 * Converts TanStack SortingState to Sequelize order format with a
 * deterministic fallback column. This prevents non-deterministic pagination
 * when rows share the same value in the sorted column (e.g., bulk imports
 * with identical timestamps).
 *
 * Column ids using dot notation (e.g. `'boundedContext.name'`) are split into
 * Sequelize's array form (`['boundedContext', 'name', dir]`) automatically.
 * The list query must `include` the corresponding association — derive it via
 * `getRelationIncludes(columns)`.
 *
 * @param sorting - TanStack sorting state
 * @param fallbackColumn - Column to ensure deterministic order (default: 'rowId')
 * @param fallbackDirection - Default direction when no sort is active (default: 'DESC')
 * @returns Sequelize-compatible order array (e.g., [['name', 'ASC'], ['rowId', 'ASC']])
 */
export function buildSortOrder(
  sorting: SortingState,
  fallbackColumn = 'rowId',
  fallbackDirection: 'ASC' | 'DESC' = 'DESC',
): string[][] {
  if (sorting.length === 0) {
    return [[fallbackColumn, fallbackDirection]];
  }

  const order = sorting.map((s) => toSequelizeOrderEntry([s.id, s.desc ? 'DESC' : 'ASC']));

  // Append fallback if not already in the sort
  if (!order.some((s) => s[0] === fallbackColumn)) {
    const primaryDirection = order[0][order[0].length - 1];
    order.push([fallbackColumn, primaryDirection]);
  }

  return order;
}
