import { setEnvironment } from "./setEnvironment";

let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}`;

export const findEnvironment = async (organization: string, userId: string, projectId?: string) => {
  try {
    const response = await fetch(
      `${url_Backend_dwinzo}/api/V1/Environments/${projectId}`,
      {
        method: "GET",
        headers: {
          Authorization: "Bearer <access_token>",  // Replace with actual token
          "Content-Type": "application/json",
          token: localStorage.getItem("token") || "",  // Coerce null to empty string
          refresh_token: localStorage.getItem("refreshToken") || "",
        },
      }
    );


    if (!response.ok) {
      throw new Error("Failed to get wall and roof visibility");
    }

    const result = await response.json();
    console.log('resultgetenv: ', result);
    if (result === "user not found") {
      const userpos = setEnvironment(
        organization,
        userId,
        false,
        false,
        false,
        40,
        true,
        projectId
      );
      return userpos;
    } else {
      return result;
    }
  } catch (error) {
    echo.error("Failed to find env");
    if (error instanceof Error) {
      throw new Error(error.message);
    } else {
      throw new Error("An unknown error occurred");
    }
  }
};
