import { Session, Room } from "./GlobalContext";
import { base } from "./Common";
const sessionApi = {
  getCurrent: async (): Promise<Session> => {
    const response = await fetch(`${base}/api/v1/games/`, {
      method: "GET",
      cache: "no-cache",
      credentials: "same-origin", /* include cookies */
      headers: {
        "Content-Type": "application/json",
      },
    });
    if (!response.ok) {
      throw new Error(`Unable to connect to Ketr Ketran game server! Try refreshing your browser in a few seconds.`);
    }
    const session : any = await response.json();
    if (!session.id) {
      session.id = session.player;
    }
    return session;
  },
  createRoom: async (name?: string): Promise<Room> => {
    const response = await fetch(`${base}/api/v1/games/${name || ''}`, {
      method: "POST",
      cache: "no-cache",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json",
      },
    });
    if (!response.ok) {
      throw new Error(`Failed to fetch session: ${response.statusText}`);
    }
    const room : Room = await response.json();
    if (!room.name) {
      room.name = room.id;
    }
    if (!room.id) {
      room.id = room.name;
    }

    return room;
  }
}
export { sessionApi };