import { useMemo } from "react";
import { isNull } from "lodash";
import { DealSchema } from "@/lib/client";
import GroupWithDealsSchema from "@/types/GroupWithDealsSchema";
import { sortByLexorank } from "@/utils/lexorank/sort";

type Props = {
    deals: DealSchema[];
};

const useDealsAndGroups = ({ deals }: Props) => {
    const dealsWithoutGroup: DealSchema[] = useMemo(
        () => deals.filter(d => isNull(d.group)),
        [deals]
    );

    const groupsWithDeals: GroupWithDealsSchema[] = useMemo(() => {
        const groupsWithDealMap = new Map<number, GroupWithDealsSchema>();

        for (const deal of deals) {
            if (isNull(deal.group)) continue;

            const groupData = groupsWithDealMap.get(deal.group.id);
            if (groupData) {
                groupData.items.push(deal);
                groupsWithDealMap.set(deal.group.id, groupData);
            } else {
                groupsWithDealMap.set(deal.group.id, {
                    ...deal.group,
                    items: [deal],
                });
            }
        }

        return sortByLexorank(groupsWithDealMap.values().toArray());
    }, [deals]);

    return {
        dealsWithoutGroup,
        groupsWithDeals,
    };
};

export default useDealsAndGroups;
