import { HttpClient, HttpParams } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, Observable, throwError } from 'rxjs';


interface AuthResponseData {
  kind: string;
  idToken: string;
  email: string;
  refreshToken: string;
  expiresIn: string;
}

export interface TokenData {
  access_token: string;
  token_type: string;
}

@Injectable({providedIn: 'root'})
export class AuthService {
  private http = inject(HttpClient);

  signup(email: string, password: string) {
    return this.http.post<TokenData>('http://localhost:8800/signup',
      {
        username: email,
        password: password
      }
    ).pipe(catchError(errorRes => {
      let errorMessage = 'An unknown error occurred!'; 
      const err = Error(errorMessage);
      if (!errorRes.error) {
        return throwError(() => err);
      }
      switch(errorRes.statusText) {
        case 'ERROR': 
          errorMessage = 'Uups...';
      }
      return throwError(() => Error(errorMessage));
    }));
  }

  login(email: string, password: string): Observable<TokenData> {
    const params = new HttpParams()
      .set('username', email)
      .append('password', password);
    return this.http.post<TokenData>('http://127.0.0.1:8800/api/login/token', params,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      }
    );
  }
}
