import request from './request';

const normalizePagedResult = (items, params = {}) => {
  const allItems = Array.isArray(items) ? items : [];
  const keyword = `${params.keyword ?? ''}`.trim();
  const role = params.role;
  const hasPaging = params.page != null || params.pageSize != null;
  const page = Math.max(1, Number(params.page) || 1);
  const pageSize = hasPaging
    ? Math.max(1, Number(params.pageSize) || 10)
    : allItems.length || 10;

  let filtered = allItems;
  if (role) {
    filtered = filtered.filter((item) => item.role === role);
  }
  if (keyword) {
    filtered = filtered.filter((item) => {
      const name = `${item.name ?? ''}`;
      const phone = `${item.phone ?? ''}`;
      return name.includes(keyword) || phone.includes(keyword);
    });
  }

  const total = filtered.length;
  const start = (page - 1) * pageSize;
  const list = hasPaging ? filtered.slice(start, start + pageSize) : filtered;

  return { list, total, page, pageSize };
};

export const getUsers = async (params = {}) => {
  const data = await request.get('/users');

  if (Array.isArray(data)) {
    return normalizePagedResult(data, params);
  }

  if (data && Array.isArray(data.list)) {
    return data;
  }

  return normalizePagedResult([], params);
};

export const createUser = (data) => {
  return request.post('/users', data);
};

export const updateUser = (id, data) => {
  return request.patch(`/users/${id}`, data);
};

export const deleteUser = (id) => {
  return request.delete(`/users/${id}`);
};

export const assignEngineerHospital = (id, hospitalId) => {
  return request.patch(`/b/users/${id}/assign-engineer-hospital`, { hospitalId });
};
