import { APIClient } from "./ApiClient";

export interface User {
  id: number;
  name: string;
  email: string;
  time_create: number;
  time_activate: number;
  active: boolean;
  admin: boolean;
  has_password: boolean;
}

export enum ReplacePasswordResponse {
  Error,
  Success,
  InvalidOldPassword,
  InvalidNewPassword,
  TooManyRequests,
}

export interface DeleteAccountTokenInfo {
  email: string;
}

export class UserApi {
  /**
   * Get current user information
   */
  static async GetUserInfo(): Promise<User> {
    return (
      await APIClient.exec({
        uri: "/user/info",
        method: "GET",
      })
    ).data;
  }

  /**
   * Update user profile
   */
  static async UpdateProfile(name: string): Promise<void> {
    await APIClient.exec({
      uri: "/user/update_profile",
      method: "POST",
      jsonData: {
        name: name,
      },
    });
  }

  /**
   * Replace user password
   */
  static async ReplacePassword(
    oldPwd: string,
    newPwd: string
  ): Promise<ReplacePasswordResponse> {
    const res = await APIClient.exec({
      uri: "/user/replace_password",
      method: "POST",
      jsonData: {
        old_password: oldPwd,
        new_password: newPwd,
      },
      allowFail: true,
    });

    if (res.status >= 200 && res.status < 300)
      return ReplacePasswordResponse.Success;

    switch (res.status) {
      case 400:
        return ReplacePasswordResponse.InvalidNewPassword;

      case 401:
        return ReplacePasswordResponse.InvalidOldPassword;

      case 429:
        return ReplacePasswordResponse.TooManyRequests;

      default:
        return ReplacePasswordResponse.Error;
    }
  }

  /**
   * Request account deletion
   */
  static async RequestAccountDeletion(): Promise<void> {
    await APIClient.exec({
      uri: "/user/request_delete",
      method: "GET",
    });
  }

  /**
   * Check delete account token
   */
  static async CheckDeleteAccountToken(
    token: string
  ): Promise<DeleteAccountTokenInfo> {
    return (
      await APIClient.exec({
        uri: "/user/check_delete_token",
        method: "POST",
        jsonData: { token: token },
      })
    ).data;
  }

  /**
   * Delete account
   */
  static async DeleteAccount(token: string): Promise<void> {
    await APIClient.exec({
      uri: "/user/delete_account",
      method: "POST",
      jsonData: { token: token },
    });
  }
}
