import http from '@/utils/http';
import { Mines, MineBasic } from '@/types/common';
import { loadMineList, storeMineList } from '@/utils/storage';

export interface RefreshData {
  basic: MineBasic;
  list: Mines;
}

export async function getMineBasic(): Promise<MineBasic> {
  const {
    ok,
    data,
    msg,
  } = await http.get<MineBasic>('/mine/basic');
  if (ok && data) {
    return data;
  }
  throw Error(msg);
}

export async function getMineList(refresh = false): Promise<Mines> {
  if (!refresh) {
    const dataCached = loadMineList();
    if (dataCached && dataCached.length) {
      return dataCached;
    }
  }

  const {
    ok,
    data,
    msg,
  } = await http.get<Mines>('/mine/list');
  if (ok && data) {
    storeMineList(data);
    return data;
  }
  throw Error(msg);
}

export async function refresh(inviter: string): Promise<RefreshData> {
  const {
    ok,
    data,
    msg,
  } = await http.get<RefreshData>('/fund/refresh', { inviter });
  if (ok) {
    if (data && data.list) {
      storeMineList(data.list);
    }
    return data as any;
  }
  throw Error(msg);
}
