import { defineStore } from 'pinia';

const baseUrl = '/api/Users';

export const auth = defineStore({
    id: 'auth',
    state: () => ({
        user: null,
        refreshTokenTimeout: null
    }),
    actions: {
        async login(client, email, password) {
            const requestBody = {
                email: email,
                password: password
            };
            try {
                const response = await client.post(`${baseUrl}/login`, requestBody)
                this.user = {
                    accessToken: response.data.accessToken,
                    refreshToken: response.data.refreshToken,
                    email: email
                }
                localStorage.setItem('jwt', this.user.accessToken);
                this.startRefreshTokenTimer();
            } catch (error) {
                throw new Error('Login failed.')
            }
        },
        logout() {
            localStorage.setItem('jwt', '');
            this.stopRefreshTokenTimer();
            this.user = null;

        },
        async refreshToken(client) {
            const response = await client.post(`${baseUrl}/refresh`, {});
            this.user.accessToken = response.accessToken;
            localStorage.setItem('jwt', this.user.accessToken);


            this.startRefreshTokenTimer();
        },
        startRefreshTokenTimer() {
            const timeout = 50 * 1000;
            this.refreshTokenTimeout = setTimeout(this.refreshToken, timeout);
        },
        stopRefreshTokenTimer() {
            clearTimeout(this.refreshTokenTimeout);
        }
    }
});
