import request from './request';

const normalizeQuery = (params = {}) => {
  if (!params || typeof params !== 'object') {
    return params;
  }

  const nextParams = { ...params };
  if (nextParams.pageSize !== undefined) {
    const parsed = Number(nextParams.pageSize);
    if (Number.isFinite(parsed)) {
      nextParams.pageSize = Math.min(100, Math.max(1, Math.trunc(parsed)));
    }
  }

  return nextParams;
};

// ==================== 医院管理 ====================
export const getHospitals = (params) => {
  return request.get('/b/organization/hospitals', { params: normalizeQuery(params) });
};

export const createHospital = (data) => {
  return request.post('/b/organization/hospitals', data);
};

export const updateHospital = (id, data) => {
  return request.patch(`/b/organization/hospitals/${id}`, data);
};

export const deleteHospital = (id) => {
  return request.delete(`/b/organization/hospitals/${id}`);
};

// ==================== 科室管理 ====================
export const getDepartments = (params) => {
  return request.get('/b/organization/departments', { params: normalizeQuery(params) });
};

export const createDepartment = (data) => {
  return request.post('/b/organization/departments', data);
};

export const updateDepartment = (id, data) => {
  return request.patch(`/b/organization/departments/${id}`, data);
};

export const deleteDepartment = (id) => {
  return request.delete(`/b/organization/departments/${id}`);
};

// ==================== 小组管理 ====================
export const getGroups = (params) => {
  return request.get('/b/organization/groups', { params: normalizeQuery(params) });
};

export const createGroup = (data) => {
  return request.post('/b/organization/groups', data);
};

export const updateGroup = (id, data) => {
  return request.patch(`/b/organization/groups/${id}`, data);
};

export const deleteGroup = (id) => {
  return request.delete(`/b/organization/groups/${id}`);
};
