import { Data } from '../../../types/data';
import { SortData } from '../../List/List.model';

/**
 * Converts the column property name and order from lower case to snake case (all caps) as required by a Postgraphile backend.
 * It will return `undefined` if the calculated value can not be found on the sortingEnum.
 * @param sort Sorting data coming from `<Explorer />`
 * @param sortingEnum Enumeration containing the values on your Postgraphile backend. Usually `{QueryName}OrderBy`.
 */
export const sortToPostGraphileOrderBy = <T extends Data, Y>(
  sort: SortData<Y> | undefined,
  sortingEnum: T,
): T[keyof T][] | undefined => {
  if (sort) {
    if (
      sort.columnSortKey &&
      Object.values(sortingEnum).includes(sort.columnSortKey)
    ) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      return [sort.columnSortKey as any];
    }

    // TODO: support numbers?
    const convertedString = `${capitalizeFirstLetter(
      String(sort?.column),
    )}${capitalizeFirstLetter(sort?.direction)}`;

    const value = sortingEnum[convertedString as keyof T];

    return value !== undefined ? [value] : undefined;
  }
};

const capitalizeFirstLetter = (s: string): string =>
  s.charAt(0).toUpperCase() + s.slice(1);
