"use client";

import { DealSchema } from "@/lib/client";
import { getProductsQueryKey } from "@/lib/client/@tanstack/react-query.gen";
import makeContext from "@/lib/contextFactory/contextFactory";
import useDealProductCrud, {
    DealProductsCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useDealProductCrud";
import useDealServicesCrud, {
    DealServicesCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useDealServicesCrud";
import {
    ProductsCrud,
    useProductsCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useProductsCrud";
import useProductServiceCrud, {
    DealProductServicesCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useProductServiceCrud";
import useDealProductsList, {
    DealProductsList,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useDealProductsList";
import useDealServicesList, {
    DealServicesList,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useDealServicesList";

type FulfillmentBaseContextState = {
    deal: DealSchema;
    productsCrud: ProductsCrud;
    dealProductsList: DealProductsList;
    dealProductsCrud: DealProductsCrud;
    dealServicesList: DealServicesList;
    dealServicesCrud: DealServicesCrud;
    productServiceCrud: DealProductServicesCrud;
};

type Props = {
    deal: DealSchema;
};

const useFulfillmentBaseContextState = ({
    deal,
}: Props): FulfillmentBaseContextState => {
    const productQueryKey = getProductsQueryKey();
    const productsCrud = useProductsCrud({ queryKey: productQueryKey });

    const dealProductsList = useDealProductsList({ dealId: deal.id });
    const dealProductsCrud = useDealProductCrud({ dealId: deal.id });

    const dealServicesList = useDealServicesList({ dealId: deal.id });
    const dealServicesCrud = useDealServicesCrud({ dealId: deal.id });

    const productServiceCrud = useProductServiceCrud({
        refetchDealProducts: dealProductsList.refetch,
    });

    return {
        deal,
        productsCrud,
        dealProductsList,
        dealProductsCrud,
        dealServicesList,
        dealServicesCrud,
        productServiceCrud,
    };
};

export const [FulfillmentBaseContextProvider, useFulfillmentBaseContext] =
    makeContext<FulfillmentBaseContextState, Props>(
        useFulfillmentBaseContextState,
        "FulfillmentBase"
    );
