import useUsersList from "../../hooks/useUsersList.tsx";
import UsersTable from "../../components/UsersTable/UsersTable.tsx";
import {UserSchema, UserService} from "../../../../client";
import {notifications} from "../../../../shared/lib/notifications.ts";

const UsersTab = () => {
    const {objects: users, refetch} = useUsersList();

    const onChange = (user: UserSchema) => {
        UserService.updateUser({
            requestBody: {
                data: {
                    ...user,
                    positionKey: user.position?.key,
                    roleKey: user.role.key
                }
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch();
        })
    }
    const onDelete = async (user: UserSchema) => {
        onChange({...user, isDeleted: true});
    }
    const onCreate = (user: UserSchema) => {
        UserService.createUser({
            requestBody: {
                data: {
                    ...user,
                    telegramId: -1
                }
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message});
            if (!ok) return;
            await refetch();
        })
    }
    return (
        <UsersTable
            items={users}
            onChange={onChange}
            onDelete={onDelete}
            onCreate={onCreate}
        />
    )
}

export default UsersTab;