import React from "react";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateProjectSchema,
    ProjectSchema,
    UpdateProjectSchema,
} from "@/lib/client";
import {
    createProjectMutation,
    deleteProjectMutation,
    updateProjectMutation,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    projects: ProjectSchema[];
    setProjects: React.Dispatch<React.SetStateAction<ProjectSchema[]>>;
    refetchProjects: () => void;
};

export type ProjectsCrud = {
    onCreate: (name: string) => void;
    onUpdate: (projectId: number, project: UpdateProjectSchema) => void;
    onDelete: (project: ProjectSchema) => void;
};

export const useProjectsCrud = ({
    projects,
    setProjects,
    refetchProjects,
}: Props): ProjectsCrud => {
    return useCrudOperations<
        ProjectSchema,
        UpdateProjectSchema,
        CreateProjectSchema
    >({
        entities: projects,
        setEntities: setProjects,
        refetch: refetchProjects,
        mutations: {
            create: createProjectMutation(),
            update: updateProjectMutation(),
            delete: deleteProjectMutation(),
        },
        getCreateEntity: name => ({ name }),
        getUpdateEntity: (old, update) => ({
            ...old,
            name: update.name ?? old.name,
        }),
        getDeleteConfirmTitle: () => "Удаление проекта",
    });
};
