import { BookingPackagePax, BookingPackageRequestRoom, PackagingAccommodationResponse, PackagingEntry, PackagingEntryLine } from '@qite/tide-client';
import { ACCOMMODATION_SERVICE_TYPE } from './query-utils';

export const getSelectedOptionsPerRoom = (details: PackagingAccommodationResponse[]) => {
  const firstResult = details[0];
  if (!firstResult?.rooms?.length) return [];

  return firstResult.rooms.map((room, roomIndex) => {
    const selectedOption = room.options.find((option) => option.isSelected) ?? room.options[0];

    return {
      roomIndex,
      option: selectedOption ?? null
    };
  });
};

export const getRoomIndexFromLine = (line: PackagingEntryLine): number => {
  if (!line.pax?.length) return 0;

  const firstPax = [...line.pax].sort((a, b) => a.order - b.order)[0];
  return firstPax?.room ?? 0;
};

export const getRequestRoomsFromPackagingSegments = (entry: PackagingEntry, segments: PackagingEntryLine[]): BookingPackageRequestRoom[] => {
  const accommodationLines = [...(segments ?? [])]
    .filter((line) => line.serviceType === ACCOMMODATION_SERVICE_TYPE && line.pax?.length > 0)
    .sort((a, b) => a.order - b.order);

  const paxById = new Map((entry.pax ?? []).map((p) => [p.id, p]));

  if (!accommodationLines.length) {
    return [];
  }

  const roomGroups: BookingPackagePax[][] = [];

  accommodationLines.forEach((line) => {
    const groupedByRoom = new Map<number, BookingPackagePax[]>();

    line.pax.forEach((linePax) => {
      const roomIndexWithinLine = Number(linePax.room ?? 0);
      const paxId = Number(linePax.paxId);
      const paxSource = paxById.get(paxId);

      const pax: BookingPackagePax = {
        id: paxSource?.id ?? paxId,
        guid: paxSource?.id?.toString() ?? paxId.toString(),
        firstName: paxSource?.firstName ?? '',
        lastName: paxSource?.lastName ?? '',
        dateOfBirth: paxSource?.dateOfBirth ?? undefined,
        age: paxSource?.dateOfBirth ? undefined : 30,
        isMainBooker: paxSource?.isMainBooker,
        email: ''
      };

      if (!groupedByRoom.has(roomIndexWithinLine)) {
        groupedByRoom.set(roomIndexWithinLine, []);
      }

      groupedByRoom.get(roomIndexWithinLine)!.push(pax);
    });

    const sortedGroups = Array.from(groupedByRoom.entries())
      .sort(([a], [b]) => a - b)
      .map(([, pax]) => pax);

    roomGroups.push(...sortedGroups);
  });

  return roomGroups.map((pax, index) => ({
    index,
    pax
  }));
};
