const BASE_URL = "http://192.168.1.91:5000";

export async function LoginOrRegister({ mobile, password }) {
  try {
    // Attempt to fetch user data
    const response = await fetch(
      `http://192.168.1.91:5000/users?mobile=${mobile}&password=${password}`
    );
    const result = await response.json();

    if (!result.length) {
      // User not found, register
      const user = await fetch(`${BASE_URL}/users`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ mobile, password, isLogged: true }),
      });
      let _userData = [{ ...user }];
      return _userData;
    } else {
      // User data found, return JSON
      return result;
    }
  } catch (err) {
    throw err; // Rethrow the error for the caller to handle
  }
}

export async function AddOrUpdateSeats({ userId, seats }) {
  try {
    const userSeat = await fetch(
      `http://192.168.1.91:5000/reservedSeats?userId=${userId}`
    );
    const result = await userSeat.json();
    if (!result.length) {
      //add seat
      console.log("add");
      const response = await fetch(BASE_URL + "/reservedSeats", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId, seats }),
      });
      const res = await response.json();
      return {
        response: res,
        isAddSeat: true,
      };
    } else {
      //update
      console.log("update");
      const response = await fetch(
        `http://192.168.1.91:5000/reservedSeats/${userId}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ seats }),
        }
      );
      const res = await response.json();

      return {
        response: res,
        isAddSeat: false,
      };
    }
  } catch (err) {
    throw err;
  }
}

export async function GetAllSeats() {
  try {
    const response = await fetch(BASE_URL + "/reservedSeats");
    return await response.json();
  } catch (err) {
    throw err;
  }
}