import { useMemoizedFn } from 'ahooks';
import Toast from '@arcblock/ux/lib/Toast';

import { client } from '../../libs/client';
import { formatAxiosError } from '../../UserCenter/libs/utils';

export default function useOrg(session) {
  const getOrgs = useMemoizedFn(async ({ search, page = 1, pageSize = 20 }) => {
    try {
      const response = await client.user.getOrgs({ search, page, pageSize });
      return response;
    } catch (error) {
      console.error(error);
      return {
        orgs: [],
        paging: {
          page,
          pageSize,
          total: 0,
        },
      };
    }
  });

  const createOrg = useMemoizedFn(async ({ name, description }) => {
    try {
      const response = await client.user.createOrg({ name, description });
      return response.data;
    } catch (error) {
      console.error(error);
      Toast.error(formatAxiosError(error));
      return null;
    }
  });

  const getOrg = useMemoizedFn(async (orgId) => {
    try {
      const data = await client.user.getOrg(orgId);
      return data;
    } catch (error) {
      session.logout();
      console.error(error);
      return null;
    }
  });

  const getCurrentOrg = useMemoizedFn(async (roleName) => {
    try {
      const response = await client.user.getRole(roleName);
      if (response.orgId) {
        const org = await getOrg(response.orgId);
        return org;
      }
      return null;
    } catch (error) {
      console.error(error);
      return null;
    }
  });

  return {
    getOrgs,
    createOrg,
    getCurrentOrg,
  };
}
