import { defineStore } from 'pinia'
// @ts-ignore
import { useCookie } from '#app' // Nuxt's built-in composable for cookies
import { authorizeUser } from '@metrixorg/websdk';
import {useRoomStore} from "./room";


export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        token: useCookie('token').value || null,
        authenticated: true,
    }),
    actions: {
        async login(form: Object) {
            // @ts-ignore
            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'); // Initialize the cookie inside the action

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

            const roomStore = useRoomStore();

            roomStore.reset();

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

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

            let push_id = useCookie('user_push_id');


            let output = false;
            // @ts-ignore
            await $api.post('/auth/init',{
                user_push_id: push_id.value !== 'undefined' ? push_id.value : ''
            },{
                headers: {
                    Authorization: `Bearer ${this.token}`,
                },
            }).then((value: { data: { data: null; }; }) => {
                this.setUser(value.data.data);
                authorizeUser(this.user.id);
                this.authenticated = true;
                output = true;
            }).catch((error: any) => {
                this.authenticated = false;
                // this.logout();
            });

            return output;
        },
    },
})
