import { DropResult } from "@hello-pangea/dnd";
import { BoardSchema, StatusSchema, StatusService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";

type Props = {
    board: BoardSchema | null;
    refetch: () => void;
}

const useStatusesDnd = ({ refetch, board }: Props) => {
    const updateStatusOrder = (status: StatusSchema, newOrdinalNumber: number) => {
        if (!board) return;

        StatusService.updateStatusOrder({
            requestBody: {
                boardId: board.id,
                statusId: status.id,
                newOrdinalNumber,
            },
        })
            .then(({ ok, message }) => {
                if (!ok) notifications.error({ message });
                refetch();
            });
    };

    const onStatusDragEnd = async (result: DropResult) => {
        if (!board) return;

        // If there is no changes
        if (!result.destination || result.destination == result.source) return;

        // Checking for valid cardId
        const statusIdStr = result.draggableId.replace("status-", "");
        const statusId = parseInt(statusIdStr);
        if (isNaN(statusId)) return;

        // Checking for valid card
        const status = board.statuses.find(board => board.id == statusId);
        if (!status) return;

        updateStatusOrder(status, result.destination.index);
    };

    return {
        onStatusDragEnd,
    };
};

export default useStatusesDnd;
