import { APIClient } from "./ApiClient";

export interface Token {
  id: number;
  name: string;
  time_create: number;
  user_id: number;
  time_used: number;
  max_inactivity: number;
  ip_net?: string;
  read_only: boolean;
  right_account: boolean;
  right_movement: boolean;
  right_inbox: boolean;
  right_file: boolean;
  right_auth: boolean;
  right_stats: boolean;
}

export interface TokenWithSecret extends Token {
  token: string;
}

export interface NewToken {
  name: string;
  ip_net?: string;
  max_inactivity: number;
  read_only: boolean;
  right_account: boolean;
  right_movement: boolean;
  right_inbox: boolean;
  right_file: boolean;
  right_auth: boolean;
  right_stats: boolean;
  right_backup: boolean;
}

export class TokensApi {
  /**
   * Get the list of tokens of the current user
   */
  static async GetList(): Promise<Token[]> {
    return (
      await APIClient.exec({
        uri: "/tokens",
        method: "GET",
      })
    ).data;
  }

  /**
   * Create a new token
   */
  static async Create(t: NewToken): Promise<TokenWithSecret> {
    return (
      await APIClient.exec({
        uri: "/token",
        method: "POST",
        jsonData: t,
      })
    ).data;
  }

  /**
   * Delete a token
   */
  static async Delete(t: Token): Promise<void> {
    await APIClient.exec({
      uri: `/token/${t.id}`,
      method: "DELETE",
    });
  }
}
