import axios from "axios";
import toast from "react-hot-toast";

const API_URL = "/api/metals";

export const createMetal = async (formData) => {
  try {
    const response = await axios.post(`${API_URL}`, formData, {
      headers: { "Content-Type": "multipart/form-data" },
    });
    toast.success(response.data.message);
    return response.data;
  } catch (error) {
    toast.error(error.response?.data?.error || "Failed to create metal");
    throw error.response?.data;
  }
};

export const getMetals = async () => {
  try {
    const response = await axios.get(`${API_URL}`);
    return response.data || [];
  } catch (error) {
    toast.error("Failed to fetch metals");
    throw error.response?.data;
  }
};

export const editMetal = async (formData) => {
  try {
    const response = await axios.put(`${API_URL}`, formData, {
      headers: { "Content-Type": "multipart/form-data" },
    });
    toast.success(response.data.message);
    return response.data;
  } catch (error) {
    toast.error(error.response?.data?.error || "Failed to update metal");
    throw error.response?.data;
  }
};

export const deleteMetal = async (id) => {
  try {
    const response = await axios.delete(`${API_URL}?id=${id}`);
    toast.success(response.data.message);
    return response.data;
  } catch (error) {
    toast.error(error.response?.data?.error || "Failed to delete metal");
    throw error.response?.data;
  }
};
