import { defineStore } from 'pinia'
import {ref, type Ref} from 'vue'
import type {GameInfo, LobbyInfo, TieInfo, TrumpInfo, WonInfo} from "@/types/GameTypes.ts";
import axios from "axios";
import {initWebSocket} from "@/services/ws.ts";

const api = window?.__RUNTIME_CONFIG__?.API_URL;

export const useIngame = defineStore('ingame', () => {
  const state: Ref<'Lobby' | 'InGame' | 'SelectTrump' | 'TieBreak' | 'FinishedMatch' | null> = ref(null);
  const data: Ref<GameInfo | LobbyInfo | TieInfo | TrumpInfo | WonInfo | null> = ref(null);

  function setIngame(newState: 'Lobby' | 'InGame' | 'SelectTrump' | 'TieBreak' | 'FinishedMatch', newData: GameInfo | LobbyInfo | TieInfo | TrumpInfo | WonInfo) {
    state.value = newState;
    data.value = newData;
  }

  async function requestGame(gameId: string) {
    await axios.get(`${api}/status/${gameId}`, {withCredentials: true}).then((response) => {
      setIngame(response.data.state, response.data.data);
    });
  }

  function clearIngame() {
    state.value = null;
    data.value = null;
  }

  return { state, data, requestGame, setIngame, clearIngame };
});
