import api from "src/api";

export const getUser = async () => {
  const { data } = await api.get("/user/current/auth");
  return data.payload;
};

export const getUsers = async () => {
  const { data } = await api.get("/user");
  return data.payload;
};

export const createUser = async (user) => {
  const { data } = await api.post("/user", user);
  return data.payload;
};

export const updateUser = async (user, id) => {
  const { data } = await api.put(`/user/${id}`, user);
  return data.payload;
};

export const deleteUser = async (id) => {
  const { data } = await api.delete(`/user/${id}`);
  return data.payload;
};

export const userTypes = async () => {
  const { data } = await api.get("/user/all/types");
  return data.payload;
};

export const uploadMyAvatar = async (file) => {
  const formData = new FormData();
  formData.append("photo", file);
  const { data } = await api.post("/user/my/avatar", formData, {
    headers: { "Content-Type": "multipart/form-data" },
  });
  return data.payload;
};

export const deleteMyAvatar = async () => {
  const { data } = await api.delete("/user/my/avatar");
  return data.payload;
};

export const getAssociados = async () => {
  const users = await getUsers();
  return users.filter((u) => u.type === "associado");
};

export const getParceiros = async () => {
  const users = await getUsers();
  return users.filter((u) => u.type === "parceiro");
};

export const getUsersPaginated = async ({ page = 1, perPage = 10, filter, type, status } = {}) => {
  const params = { page, per_page: perPage };
  if (type)   params.type   = type;
  if (status) params.status = status;
  if (filter) params.search = filter;
  const { data } = await api.get("/user/paginated", { params });
  return { data: { result: data.payload } };
};

export const getAssociadosPaginated = async (params = {}) =>
  getUsersPaginated({ ...params, type: "associado" });

export const setUserOnLeave = async (id) => {
  const { data } = await api.put(`/user/${id}/on-leave`);
  return data.payload;
};

export const updateMyProfile = async (payload) => {
  const { data } = await api.put("/user/my/profile", payload);
  return data.payload;
};

export const importAssociados = async (file) => {
  const formData = new FormData();
  formData.append("file", file);
  const { data } = await api.post("/user/import/associados", formData, {
    headers: { "Content-Type": "multipart/form-data" },
  });
  return data.payload;
};
