export type NotificationMessageTimestampedId = {
  id: number;
  createdAt: string | null | undefined;
};

export function selectNotificationMessageIdsToDelete(
  items: NotificationMessageTimestampedId[],
  keepLatestCount = 1,
) {
  const normalizedKeepLatestCount = Number.isInteger(keepLatestCount) && keepLatestCount > 0 ? keepLatestCount : 1;

  return items
    .slice()
    .sort((left, right) => {
      const leftCreatedAt = Date.parse(left.createdAt ?? '');
      const rightCreatedAt = Date.parse(right.createdAt ?? '');

      if (Number.isFinite(leftCreatedAt) && Number.isFinite(rightCreatedAt) && leftCreatedAt !== rightCreatedAt) {
        return rightCreatedAt - leftCreatedAt;
      }

      return right.id - left.id;
    })
    .slice(normalizedKeepLatestCount)
    .map((item) => item.id);
}
