import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import performRequest from "@/backend.js";
import logger from "@/logger.js";


export const useUsersStore = defineStore('users', {
    state: () => ({
        users: [],
        loading: false,
        pagination: {},
        query: {},
    }),
    getters: {
        getById: (state) => {
            return (id) => state.users.find(p => p.id === id)
        }
    },
    actions: {
        async setQuery(query) {
            this.query = query;
            await this.load();
        },
        async updateUser(user) {
            const body = {
                firstname: user.firstname,
                lastname: user.lastname,
                mail: user.mail,
                workday_id: user.workday_id,
                groups: user.groups
            }

            await performRequest(this, "PUT", `${config.backendUrl}/users/`, body, false);
        },
        async load() {

            this.loading = true;

            const params = new URLSearchParams();

            if (this.query?.page)
                params.append('page', this.query.page);

            if (this.query?.pageSize)
                params.append('limit', this.query.pageSize);

            const endpoint = '/users';
            const url = `${config.backendUrl}${endpoint}/${params.size === 0 ? '' : '?'}${params.toString()}`;
            const {data: data, headers: headers} = await performRequest(this, "GET", url, null, true);

            this.pagination = {
                page: parseInt(headers.get('X-Current-Page')),
                pageCount: parseInt(headers.get('X-Page-Count')),
                totalCount: parseInt(headers.get('X-Total-Count'))
            };

            this.loading = false;
            this.empty = data.users.length === 0;
            this.users = data.users;
        }
    }

});
