import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateDealSchema,
    DealSchema,
    StatusSchema,
    UpdateDealSchema,
} from "@/lib/client";
import {
    createDealMutation,
    deleteDealMutation,
    updateDealMutation,
} from "@/lib/client/@tanstack/react-query.gen";

import { getNewLexorank } from "@/utils/lexorank/generation";

type UseDealsOperationsProps = {
    deals: DealSchema[];
    boardId?: number;
    statuses: StatusSchema[];
    queryKey: any[];
};

export type DealsCrud = {
    onCreate: (entity: Partial<CreateDealSchema>) => void;
    onUpdate: (dealId: number, deal: UpdateDealSchema) => void;
    onDelete: (deal: DealSchema, onSuccess?: () => void) => void;
};

export const useDealsCrud = ({
    deals,
    boardId,
    statuses,
    queryKey,
}: UseDealsOperationsProps): DealsCrud => {
    return useCrudOperations<DealSchema, UpdateDealSchema, CreateDealSchema>({
        key: "getDeals",
        queryKey,
        mutations: {
            create: createDealMutation(),
            update: updateDealMutation(),
            delete: deleteDealMutation(),
        },
        getCreateEntity: data => {
            if (!boardId || statuses.length === 0) return null;
            const firstStatus = statuses[0];
            const filteredDeals = deals.filter(
                d => d.status.id === firstStatus.id
            );
            let firstDeal: DealSchema | null = null;
            if (filteredDeals.length > 0) {
                firstDeal = filteredDeals[0];
            }
            const newLexorank = getNewLexorank(
                null,
                firstDeal ? LexoRank.parse(firstDeal.lexorank) : null
            );
            return {
                name: data.name!,
                boardId,
                statusId: firstStatus.id,
                lexorank: newLexorank.toString(),
            };
        },
        getUpdateEntity: (old, update) => ({
            ...old,
            name: update.name ?? old.name,
            lexorank: update.lexorank ?? old.lexorank,
            status: update.statusId
                ? { ...old.status, id: update.statusId }
                : old.status,
            board: update.boardId
                ? { ...old.board, id: update.boardId }
                : old.board,
        }),
        getDeleteConfirmTitle: () => "Удаление сделки",
    });
};
