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


export type DepartmentSectionCrud = {
    onCreate: (element: DepartmentSectionBaseSchema) => void,
    onDelete: (element: DepartmentSectionSchema) => void,
    onChange: (element: DepartmentSectionSchema) => void
}

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

const useDepartmentSectionCrud = ({ fetchDepartments }: Props): DepartmentSectionCrud => {
    return useCRUD<DepartmentSectionSchema, DepartmentSectionBaseSchema>({
        onChange: section => {
            DepartmentService.updateSection({
                requestBody: { section },
            })
                .then(({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchDepartments();
                })
                .catch(err => console.log(err));
        },
        onCreate: section => {
            DepartmentService.createSection({
                requestBody: { section },
            })
                .then(({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchDepartments();
                })
                .catch(err => console.log(err));
        },
        onDelete: section => {
            DepartmentService.deleteSection({ sectionId: section.id })
                .then(({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchDepartments();
                })
                .catch(err => console.log(err));
        },
    });
};

export default useDepartmentSectionCrud;
