import { defineStore } from 'pinia'
import {ref, type Ref} from 'vue'
import axios from "axios";

const api = window?.__RUNTIME_CONFIG__?.API_URL;

export const useUserInfo = defineStore('userInfo', () => {
  const username: Ref<string | null> = ref(null);
  const userId: Ref<number | null> = ref(null);
  const gameId: Ref<string | null> = ref(null);

  function setUserInfo(name: string, id: number) {
    username.value = name;
    userId.value = id;
  }

  function setGameId(id: string) {
    gameId.value = id;
  }

  async function requestState() {
    await axios.get(`${api}/status`, {withCredentials: true}).then((response) => {
      console.log("STATUS DATA:" + response.data.status + response.data.inGame)
      username.value = response.data.username;
      if (response.data.gameId) {
        console.log("GAMEID:" + response.data.gameId)
        gameId.value = response.data.gameId;
      }
    })
  }

  function clearUserInfo() {
    username.value = null;
    userId.value = null;
  }

  function clearGameId() {
    gameId.value = null;
  }

  return { username, userId, gameId, setUserInfo, requestState, clearUserInfo, setGameId, clearGameId };
});
