import axios from "axios";

const API_URL = "http://192.168.0.118:9000";

export async function listLocations() {
  try {
    const response = await axios.get(`${API_URL}/locations/all`);
    if (!response) {
      return "No locations found";
    }

    return response.data.map(location => ({
      ...location,
      imageSource: normalizeImageSource(location.image)
    }));
  } catch (error) {
    console.error("Error fetching locations:", error);
    throw error;
  }
}

const normalizeImageSource = (image) => {
  if (!image) return null;

  if (typeof image === 'string') {
    if (image.startsWith('http://') || image.startsWith('https://')) {
      return { uri: image };
    }

    if (image.startsWith('data:image')) {
      return { uri: image };
    } else if (image.length > 100) {
      return { uri: `data:image/jpeg;base64,${image}` };
    }
  }

  return null;
}

export async function getLocation(id) {
  try {
    const location = await axios.get(`${API_URL}/locations/${id}`);
    if (!location) {
      console.error("Could not find location");
      return("Location not found");
    }

    return [...location.data, {image: normalizeImageSource(location.image)}];
  } catch (error) {
    console.error("Error fetching location:", error);
    throw error;
  }
}

export async function addLocation(location) {
  try {
    const response = await axios.post(`${API_URL}/locations/add`, location, {
      headers: {
        "Content-Type": "application/json",
      },
    });
    if (!response) {
      console.log("Error adding location");
      return("Failed to add location");
    }
    return response.data;
  } catch (error) {
    console.error("Error adding location:", error);
    throw error;
  }
}

export async function updateLocation(id, location) {
  try {
    const response = await axios.put(`${API_URL}/locations/${id}`, location, {
      headers: { "Content-Type": "application/json" },
    });
    if (!response) {
      console.log("Failed to update location");
      return("Failed to update location");
    }
    return response.data;
  } catch (error) {
    console.error("Error while updating location:", error);
    throw error;
  }
}

export async function deleteLocation(id) {
  try {
    const response = await axios.delete(`${API_URL}/locations/${id}`);
    if (!response) {
      console.log("Error deleting location");
      return("Failed to delete location");
    }
    return response.data;
  } catch (error) {
    console.error("Error while deleting location:", error);
    throw error;
  }
}
