import { useCRUD } from "../../../../../hooks/useCRUD.tsx";
import { DepartmentBaseSchema, DepartmentSchema, DepartmentService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";


export type DepartmentCrud = {
    onCreate: (element: DepartmentBaseSchema) => void,
    onDelete: (element: DepartmentSchema) => void,
    onChange: (element: DepartmentSchema) => void
}

type Props = {
    fetchDepartments: () => void;
}

const useDepartmentCrud = ({ fetchDepartments }: Props): DepartmentCrud => {
    return useCRUD<DepartmentSchema, DepartmentBaseSchema>({
        onChange: department => {
            DepartmentService.updateDepartment({
                requestBody: { department },
            })
                .then(({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchDepartments();
                })
                .catch(err => console.log(err));
        },
        onCreate: department => {
            DepartmentService.createDepartment({
                requestBody: { department },
            })
                .then(({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchDepartments();
                })
                .catch(err => console.log(err));
        },
        onDelete: department => {
            DepartmentService.deleteDepartment({ departmentId: department.id })
                .then(({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchDepartments();
                })
                .catch(err => console.log(err));
        },
    });
};

export default useDepartmentCrud;