import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';
import { JwtSigninResponse } from '../model/jwt-signin-response.model';
import { map } from 'rxjs/operators';
import { API_BASE_URL } from 'src/modules/common/type/injection-token.type';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(
    @Inject(API_BASE_URL) private apiBaseUrl: string,
    private httpClient: HttpClient
  ) {}

  public authenticate(
    username: string,
    password: string
  ): Observable<JwtSigninResponse> {
    return this.httpClient
      .post<JwtSigninResponse>(`${this.apiBaseUrl}/auth/signin`, {
        username,
        password
      })
      .pipe(
        map(res => {
          sessionStorage.setItem('username', username);
          let tokenStr = res.tokenType + ' ' + res.accessToken;
          sessionStorage.setItem('token', tokenStr);
          return res;
        })
      );
  }

  isLoggedIn() {
    const user = sessionStorage.getItem('username');
    return !(null === user);
  }

  logOut() {
    sessionStorage.removeItem('username');
  }
}
