import http from '@/utils/http';
import { AreaCode, SendCodeType } from '@/types/common';
import { encodePhone, encryptPwd } from '@/utils/transform';

export enum CheckResult {
  Login = 0,
  Register = 1,
}

export async function checkExistence(areacode: AreaCode, phone: string): Promise<CheckResult> {
  const { code, msg } = await http.get('/sign/check', { phone: encodePhone(areacode, phone) });
  if (code !== CheckResult.Login && code !== CheckResult.Register) {
    throw Error(msg);
  }
  return code as CheckResult;
}

export async function signIn(areacode: AreaCode, phone: string, password: string): Promise<string> {
  const { ok, msg, data } = await http.post(
    '/sign/in',
    {
      phone: encodePhone(areacode, phone),
      password: encryptPwd(password),
    },
  );
  if (!ok || !data || !data.token) {
    throw Error(msg);
  }
  return data.token;
}

export async function signUp(areacode: AreaCode, phone: string, password: string, code: string, inviter: string): Promise<string> {
  const { ok, msg, data } = await http.post(
    '/sign/upwi',
    {
      phone: encodePhone(areacode, phone),
      password: encryptPwd(password),
      inviter,
      code,
    },
  );
  if (!ok || !data || !data.token) {
    throw Error(msg);
  }
  return data.token;
}

export async function reset(areacode: AreaCode, phone: string, password: string, code: string): Promise<void> {
  const { ok, msg, data } = await http.post(
    '/sign/forget',
    {
      phone: encodePhone(areacode, phone),
      password: encryptPwd(password),
      code,
    },
  );
  if (!ok) {
    throw Error(msg);
  }
}

export async function sendCode(areacode: AreaCode, phone: string, type: SendCodeType) {
  const { ok, msg } = await http.post(
    '/sign/send',
    {
      phone: encodePhone(areacode, phone),
      type,
    },
  );
  if (ok) {
    return true;
  }
  throw Error(msg);
}
