import { PhotosData } from './types';

export function groupByDate(items: PhotosData[]) {
  const groupedByDate = items.reduce((acc: { [key: string]: PhotosData[] }, item) => {
    const { date } = item;
    if (!acc[date]) {
      acc[date] = [];
    }
    acc[date].push(item);
    return acc;
  }, {});

  return Object.entries(groupedByDate)
    .map(([date, photos]) => ({
      date: date,
      photos: photos as PhotosData[]
    }))
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
}

const normalizeDate = (dateStr: string) => {
  const parts = dateStr.split('-');
  const normalizedDate = `${parts[0]}-${parts[1] || '12'}-${parts[2] || '01'}`;
  return normalizedDate;
};

export const compareDates = (date1: string, date2: string) => {
  const normalizedDate1 = normalizeDate(date1);
  const normalizedDate2 = normalizeDate(date2);
  if (normalizedDate1 > normalizedDate2) {
    return -1;
  }
  if (normalizedDate1 < normalizedDate2) {
    return 1;
  }
  return 0;
};
