import Http from "../utils/Http";

export interface PogResp {
  protocolId: number;
  requestId: number;
  code: number;
  success: boolean;
  data: any;
  msg: string;
}

export interface PogLoginResp {
  token: string;
  expire: number;
  wsUrl: string;
}

export default class PogHttp {
  private static readonly client = "YbVHPrXS";
  private static readonly HTTP_HEAD = "https://zombies.telgather.com/platform";
  private static _ins: PogHttp;

  public static get ins(): PogHttp {
    return (this._ins ??= new PogHttp());
  }

  public lastError: string = "";

  public async _apiRequest(path: string, params: any): Promise<any> {
    const headers = {
      client: PogHttp.client,
    };
    const resp = await Http.get(PogHttp.HTTP_HEAD + path, params, headers);
    const pogResp = resp as PogResp;
    if (pogResp.code !== 200) {
      this.lastError = pogResp.msg;
      return null;
    }

    return pogResp.data;
  }

  public async loginByWalletAddress(address: string): Promise<PogLoginResp> {
    const path = "/pog-service/login/wallet";
    const res = await this._apiRequest(path, { address });
    return res;
  }

  async loginByTgParams(
    initDataRaw: string,
    tgWebAppStartParam: string
  ): Promise<PogLoginResp> {
    const path = "/pog-service/login/tg";
    if (!tgWebAppStartParam) {
      tgWebAppStartParam = "ABC";
    }
    const res = await this._apiRequest(path, {
      params: initDataRaw,
      inviteCode: tgWebAppStartParam,
    });
    return res;
  }

  async allConfig(): Promise<any> {
    const path = "/pog-service/login/config";
    const res = await this._apiRequest(path, {});
    return res;
  }
}
