import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { StorageService } from './storage.service';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private token?: string;

  constructor(
    private readonly storage: StorageService,
    private readonly api: ApiService
  ) {
    this.token = this.storage.token;
  }
  get isLogin(): boolean {
    return this.token != undefined;
  }

  async login(params: Auth.LoginParams): Promise<Auth.LoginResponse> {
    const result = await this.api.auth.login(params).catch(err => {
      throw err;
    });
    await this.afterLogin(result);
    return result;
  }

  getToken(): string | undefined {
    return this.token;
  }
  async autoLogin(): Promise<boolean> {
    this.token = this.storage.token;
    if (!this.token) {
      return true;
    }
    return true;
  }

  private async afterLogin(result: Auth.LoginResponse) {
    this.storage.token = result.token;
    const autoLogin = await this.autoLogin();
    if (!autoLogin) {
      return undefined;
    }
    return result;
  }
}
