import api, { fileUrl } from "./api.js";
import { unwrapData, unwrapList } from "./http.js";

export async function listUsers(query = {}) {
  const res = await api.get("/users", { params: query });
  return unwrapList(res);
}

export async function getUser(userId) {
  const res = await api.get(`/users/${userId}`);
  return unwrapData(res);
}

export async function createUser(payload, photoFile) {
  const fd = new FormData();
  Object.entries(payload || {}).forEach(([k, v]) => {
    if (v == null) return;
    fd.append(k, typeof v === "object" ? JSON.stringify(v) : v);
  });
  if (photoFile) fd.append("photo", photoFile);
  const res = await api.post("/users", fd);
  return unwrapData(res);
}

export async function updateUser(userId, payload, photoFile) {
  const fd = new FormData();
  Object.entries(payload || {}).forEach(([k, v]) => {
    if (v == null) return;
    fd.append(k, typeof v === "object" ? JSON.stringify(v) : v);
  });
  if (photoFile) fd.append("photo", photoFile);
  const res = await api.put(`/users/${userId}`, fd);
  return unwrapData(res);
}

/** Status-only update via JSON (reliable toggle; avoids multipart parsing issues). */
export async function updateUserStatus(userId, statusId) {
  const res = await api.put(`/users/${userId}`, { status_id: Number(statusId) });
  return unwrapData(res);
}

export async function deleteUser(userId) {
  const res = await api.delete(`/users/${userId}`);
  return unwrapData(res);
}

export function userPhotoUrl(userId) {
  return fileUrl(`/users/${userId}/photo`);
}

export async function listUserRoles(query = {}) {
  const res = await api.get("/user_role", { params: query });
  return unwrapList(res);
}

export async function createUserRole(payload) {
  const res = await api.post("/user_role", payload);
  return unwrapData(res);
}

export async function deleteUserRole(userRoleId) {
  const res = await api.delete(`/user_role/${userRoleId}`);
  return unwrapData(res);
}

export async function listUserCityMaps(query = {}) {
  const res = await api.get("/admin_level_user_multi_city_map", { params: query });
  return unwrapList(res);
}

export async function createUserCityMap(payload) {
  const res = await api.post("/admin_level_user_multi_city_map", payload);
  return unwrapData(res);
}

export async function deleteUserCityMap(userId, cityId) {
  const res = await api.delete(`/admin_level_user_multi_city_map/${userId}/${cityId}`);
  return unwrapData(res);
}

export async function listUsersLogs(query = {}) {
  const res = await api.get("/users_logs", { params: query });
  return unwrapList(res);
}
