import { create } from "zustand";
import api from "../services/api"
import { toast } from "react-hot-toast"
const useStore = create((set) => ({
    authUser: null,
    isAuthenticated: false,
    login: async(username, password) => {
        try {
            const response = await api.post("/auth/login", {
                username: username,
                password: password
            });

            if(response.status == 200) {
                set({ authUser: response.data.username, isAuthenticated: true });
                toast.success(response.data.message);
            }else{
                toast.error(response.data.message);
            }
        } catch (error) {
            console.log(error)
        }
    },
    register: async(username, password) => {
        try {
            const response = await api.post("/auth/register", {
                username: username,
                password: password
            });
            if(response.status == 201) {
                set({ authUser: response.data.username, isAuthenticated: true });
                toast.success(response.data.message);
            }else{
                toast.error(response.data.message);
            }
        } catch (error) {
            console.log(error)
        }
    },
    logout: async() => {
        try {
            const response = await api.get("/auth/logout");
            if(response.status == 200) {
                set({ authUser: null, isAuthenticated: false });
                toast.success(response.data.message);
            }else{
                set({ authUser: null, isAuthenticated: false });
                toast.error(response.data.message);
            }
        } catch (error) {
            console.log(error)
        }
    },
    promote: async(username, code) => {
        try {
            const response = await api.post("/auth/promote", {
                username: username,
                code: code
            });
            if(response.status == 201) {
                set({ authUser: response.data.username, isAuthenticated: true });
                toast.success(response.data.message);
            }else{
                toast.error(response.data.message);
            }
        } catch (error) {
            console.log(error)
        }
    },
    checkAuth: async() => {
        try {
            const response = await api.get("/auth/check");
            if(response.status == 200) {
                set({ authUser: response.data.username, isAuthenticated: true });
            }
        } catch (error) {
            console.log(error)
        }
    },
}));

export default useStore;