import {defineStore} from 'pinia';
import {ref} from 'vue';
import apiClient from "@/network/axiosSetup";
import {useRoute, useRouter} from "vue-router";
import {useToast} from "primevue/usetoast";
import {User} from "@/models/user";

export const useUserStore = defineStore('user', () => {
    const toast = useToast();
    const user = ref<User | null>(null);
    const loadingUser = ref(true);
    const router = useRouter();
    const route = useRoute();
    const isAuthorized = ref(false);

    async function fetchUserProfile() {
        // Убираем проверку на `loadingUser`, чтобы не блокировать запрос
        if (!user.value) {
            loadingUser.value = true;
            try {
                await apiClient.get('/auth/me')
                    .then((res: any) => {
                        user.value = res.data
                        isAuthorized.value = true
                    })
                    .catch((err: Error) => {
                        console.log(err)
                        throw err
                    })
            } catch (error) {
                console.error('Ошибка при загрузке данных пользователя:', error);
                user.value = null;
            } finally {
                loadingUser.value = false;  // Сбрасываем флаг `loadingUser` в `false` после завершения
            }
        }
    }

    async function tgLogin(id: number, first_name: string, last_name: string, username: string, photo_url: string, auth_date: string, hash: string) {
        try {
            let response;

            response = await apiClient.post('/auth/tg-login', {
                id: id,
                first_name: first_name,
                last_name: last_name,
                username: username,
                photo_url: photo_url,
                auth_date: auth_date,
                hash: hash,
            });


            const token = response.data.token;
            console.log(token);
            localStorage.setItem('token', token);
            apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            toast.add({severity: 'success', summary: 'Вход выполнен', detail: 'Добро пожаловать!', life: 3000})
            await fetchUserProfile();
            await router.push(route.query['back'] ? route.query['back'].toString() : '/');
        } catch (error: any) {
            console.error(error);
            toast.add({
                severity: 'error',
                summary: 'Ошибка авторизации',
                detail: error.response.data.message,
                life: 3000
            })
        }
    }

    async function tgLoginData(initData: string, hash:string) {
        try {
            let response;

            response = await apiClient.post('/auth/tg-login', {
                initData: initData,
                hash: hash,
            });


            const token = response.data.token;
            console.log(token);
            localStorage.setItem('token', token);
            apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            toast.add({severity: 'success', summary: 'Вход выполнен', detail: 'Добро пожаловать!', life: 3000})
            await fetchUserProfile();
            await router.push(route.query['back'] ? route.query['back'].toString() : '/');
        } catch (error: any) {
            console.error(error);
            toast.add({
                severity: 'error',
                summary: 'Ошибка авторизации',
                detail: error.response.data.message,
                life: 3000
            })
        }
    }

    // Основная функция для логина
    async function login(username: string, password: string) {

        try {
            let response;

            response = await apiClient.post('/auth/login', {
                username: username,
                password: password,
            });


            const token = response.data.token;
            console.log(token);
            localStorage.setItem('token', token);
            apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            toast.add({severity: 'success', summary: 'Вход выполнен', detail: 'Добро пожаловать!', life: 3000})
            await fetchUserProfile();
            await router.push(route.query['back'] ? route.query['back'].toString() : '/');
        } catch (error: any) {
            console.error(error);
            toast.add({
                severity: 'error',
                summary: 'Ошибка авторизации',
                detail: error.response.data.message,
                life: 3000
            })
        }
    }

    async function register(username: string, password: string, firstName: string) {
        try {
            let response = await apiClient.post('/auth/register', {
                username: username,
                password: password,
                firstName: firstName
            })
            return response.data
        } catch (error) {
            // console.error(error);
            throw error
        }
    }

    async function linkGoogleDrive(code: string) {
        try {
            await apiClient.post('/auth/me/google-drive', {
                code: code
            });
            toast.add({severity: 'success', summary: 'Google Drive connected', detail: 'Successful!', life: 3000})
            await fetchUserProfile(); // refresh user info to get updated isGoogleDriveLinked
        } catch (error: any) {
            console.error(error);
            toast.add({
                severity: 'error',
                summary: 'Connection error',
                detail: error.response?.data?.message || 'Error occurred while linking Google Drive',
                life: 3000
            })
        }
    }


    return {user, loadingUser, fetchUserProfile, tgLogin, tgLoginData, register, linkGoogleDrive, isAuthorized};
});
