export type SearchSortField = 'created_at' | 'updated_at' | 'priority' | 'status';
export type SearchSortDirection = 'asc' | 'desc';

export type SearchSortKey =
  | 'created_at_desc'
  | 'created_at_asc'
  | 'updated_at_desc'
  | 'updated_at_asc'
  | 'priority_desc'
  | 'priority_asc'
  | 'status_desc'
  | 'status_asc';

export interface SearchSortOption {
  key: SearchSortKey;
  sort_by: SearchSortField;
  sort_direction: SearchSortDirection;
  labelKey: string;
}

export const SEARCH_SORT_OPTIONS: SearchSortOption[] = [
  { key: 'created_at_desc', sort_by: 'created_at', sort_direction: 'desc', labelKey: 'search:sort.latest' },
  { key: 'created_at_asc', sort_by: 'created_at', sort_direction: 'asc', labelKey: 'search:sort.oldest' },
  { key: 'updated_at_desc', sort_by: 'updated_at', sort_direction: 'desc', labelKey: 'search:sort.updatedLatest' },
  { key: 'updated_at_asc', sort_by: 'updated_at', sort_direction: 'asc', labelKey: 'search:sort.updatedOldest' },
  { key: 'priority_desc', sort_by: 'priority', sort_direction: 'desc', labelKey: 'search:sort.priorityHigh' },
  { key: 'priority_asc', sort_by: 'priority', sort_direction: 'asc', labelKey: 'search:sort.priorityLow' },
  { key: 'status_desc', sort_by: 'status', sort_direction: 'desc', labelKey: 'search:sort.status' },
  { key: 'status_asc', sort_by: 'status', sort_direction: 'asc', labelKey: 'search:sort.statusAsc' },
];

export const DEFAULT_SEARCH_SORT: SearchSortKey = 'created_at_desc';

export function parseSearchSortKey(value: string | null): SearchSortKey {
  const match = SEARCH_SORT_OPTIONS.find((option) => option.key === value);
  return match?.key ?? DEFAULT_SEARCH_SORT;
}

export function getSearchSortParams(key: SearchSortKey): {
  sort_by: SearchSortField;
  sort_direction: SearchSortDirection;
} {
  const option = SEARCH_SORT_OPTIONS.find((item) => item.key === key) ?? SEARCH_SORT_OPTIONS[0];
  return {
    sort_by: option.sort_by,
    sort_direction: option.sort_direction,
  };
}
