// @ts-ignore
import {defineStore} from 'pinia'
// @ts-ignore
import {useCookie} from '#app'


export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        token: useCookie('token',{ maxAge: 60 * 60 * 24 * 365 }).value || null,
        authenticated: true,
    }),
    actions: {
        async login(form: Object) {
            const {$api} = useNuxtApp();  // Access NuxtApp

            // @ts-ignore
            await $api.post('/auth/login', form).then((value) => {
                this.setToken(value.data.data.token)

                setTimeout(() => {
                    this.init();

                }, 300);
            }).catch((error: any) => {
                console.error('Login error:', error)
            });

        },
        setToken(token: string) {
            const tokenCookie = useCookie('token',{ maxAge: 60 * 60 * 24 * 365 }); // Initialize the cookie inside the action

            // @ts-ignore
            this.token = token
            tokenCookie.value = token; // Store the token in cookies
        },
        setUser(user: any) {
            // @ts-ignore
            this.user = user
        },
        logout() {
            const tokenCookie = useCookie('token',{ maxAge: 60 * 60 * 24 * 365 }); // Access the cookie
            const router = useRouter();

            // @ts-ignore
            this.token = null
            // @ts-ignore
            this.user = null
            // @ts-ignore
            this.authenticated = false;
            tokenCookie.value = ''; // Clear the token from the cookie

            router.push('/auth')
        },
        async init() {
            // @ts-ignore
            this.authenticated = true;
            const {$api} = useNuxtApp();  // Access NuxtApp
            // @ts-ignore
            if (!this.token) {
                // @ts-ignore
                this.authenticated = false;
                return
            }

            let push_id = useCookie('user_push_id');

            // @ts-ignore
            await $api.post('/auth/init', {
                user_push_id: push_id.value !== 'undefined' ? push_id.value : ''
            }).then((value: { data: { data: null; }; }) => {
                this.setUser(value.data.data);
                // @ts-ignore
                this.authenticated = true;
            }).catch((error: any) => {
                console.error('Failed to fetch user:', error)
                // @ts-ignore
                this.authenticated = false;
                // this.logout();
            })
        },
    },
})
