import {defineStore} from "pinia";
import axios from "axios";

export const useAuthStore = defineStore('auth', {
    state: () => ({
        baseUrl : process.env.VUE_APP_BASE_URL,
        clientId : process.env.VUE_APP_CLIENT_ID,
        clientSecret : process.env.VUE_APP_CLIENT_SECRET,
        token: null,
        refresh_token: null,
        user: null
    }),
    getters: {
        isLoggedIn: (state) => !!state.token && !!state.user,
    },
    actions: {
        async register(username, password, re_password) {
            const response =await axios.post(this.baseUrl + '/auth/users/', {
                username: username,
                password: password,
                re_password: re_password
            });

            console.log("✅ Registration success:", response.data);
        },
        async login(username, password) {
            // preparing data
            const data = new URLSearchParams()
            data.append('grant_type', 'password')
            data.append('client_id', this.clientId)
            data.append('client_secret', this.clientSecret)
            data.append('username', username)
            data.append('password', password)

            const response = await axios.post(`${this.baseUrl}`+'/oauth/token/',data.toString(), {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            })

            const { access_token, refresh_token } = response.data;
            const user = await axios.get(this.baseUrl + '/auth/users/me', {
                headers: {
                    Authorization: `Bearer ${access_token}`
                }
            }).then(res => res.data)

            this.refresh_token = refresh_token
            this.token = access_token
            this.user = user

            console.log(JSON.stringify(user));
            localStorage.setItem('token', this.token)
            localStorage.setItem('user', JSON.stringify(user))
            console.log("✅ Logged in as:", this.user.username);
        },
        async logout() {
            if(this.token){
                await axios.post(this.baseUrl + '/oauth/revoke_token/', {
                    token: this.token,
                    client_id: this.clientId,
                    client_secret: this.clientSecret
                },
                {
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                });
            }else{
                console.log("No token found");
            }

            this.token = null;
            this.user = null;
            localStorage.removeItem('token')
            localStorage.removeItem('user')
        },
        restoreSession() {
            const savedToken = localStorage.getItem('token')
            const savedUser = localStorage.getItem('user')

            if (savedToken && savedUser) {
            this.token = savedToken
                this.user = JSON.parse(savedUser)
            }
        }
    }
})