import { Injectable } from '@angular/core'; 
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, tap, catchError } from 'rxjs';
import { ApiService } from './api.service';
import { LoginData } from '../interface/auth';
import { jwtDecode } from 'jwt-decode';
import { StorageService } from './storage.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class AuthService extends ApiService {
  private authUrl = `${this.baseUrl}auth/login`;
  private logoutUrl = `${this.baseUrl}auth/logout`;
  private registerUrl = `${this.baseUrl}auth/register`;
  
  constructor(
    http: HttpClient, 
    private storageService: StorageService, 
    private toast: ToastrService,
  ) {
    super(http);
  }

  login(data: LoginData): Observable<any> {
    const headers = new HttpHeaders({
      Authorization: 'Basic ' + btoa(`${data.email}:${data.password}`)
    });
  
    const formData = new FormData();
    formData.append('remember_me', data.rememberMe ? 'true' : 'false');
  
    return this.http.post<any>(this.authUrl, formData, { headers }).pipe(
      tap(response => {
        const accessToken = response.data.token;
        this.storageService.saveToken(accessToken, data.rememberMe ?? false);
  
        const jwtToken = response.data.jwtToken;
        const decodedToken: any = jwtDecode(jwtToken);
  
        this.storageService.saveUserData(decodedToken.user.fullname, decodedToken.user.avatar);
      }),
      catchError(error => {
        this.toast.error('Login failed, please try again');
        throw error;
      })
    );
  }

  logout(): Observable<any> {
    const token = this.storageService.getToken();
    const headers = new HttpHeaders({
      Authorization: `Bearer ${token}` 
    });

    return this.http.post<any>(this.logoutUrl, {}, { headers }).pipe(
      tap(() => {
        this.storageService.clearToken();
        this.storageService.clearUserData();
      }), 
    );
  }

  register(data: any): Observable<any> {
    const headers = new HttpHeaders({});
    return this.http.post<any>(this.registerUrl, data, { headers });
  }

  getUserFullName(): string | null {
    return this.storageService.getUserFullName();
  }

  getAvatar(): string | null {
    return this.storageService.getAvatar();
  }
}
