import {Token} from '@makeflow/gateway-shared';
import {action, computed, observable} from 'mobx';

import {APIService} from './api-service';

export class TokenService {
  @observable
  private _tokens: Token[] | undefined;

  @computed
  get tokens(): Token[] {
    return this._tokens || [];
  }

  constructor(private apiService: APIService) {}

  async fetchTokens(): Promise<void> {
    let tokens = await this.apiService.post<Token[]>(
      '/api/token/get-active-tokens',
    );

    this.setTokens(tokens);
  }

  async generateToken(label: string): Promise<string> {
    let token = await this.apiService.post<string>('/api/token/generate', {
      label,
    });

    await this.fetchTokens();

    return token;
  }

  async deactivateToken(id: number): Promise<void> {
    await this.apiService.post('/api/token/deactivate-token', {
      id,
    });

    await this.fetchTokens();
  }

  @action
  private setTokens(tokens: Token[]): void {
    this._tokens = tokens;
  }
}
