import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs';
import { apiTemp } from '../../environments/environment.prod';

@Injectable({
  providedIn: 'root'
})
export class AdvicesService {

  constructor(private _http: HttpClient) {}

  getAdvice(id: string, idUser: string, line: number){
    return this.getQuery(`get-advice/${id}/${idUser}/${line}`).pipe(map((data: any) => data));
  }

  getAdvices(idUser: string, line: number){
    return this.getQuery(`get-advices/${idUser}/${line}`).pipe(map((data: any) => data));
  }

  getDownloadToken(id: string, idUser: string, line: number){
    return this.getQuery(`get-download-token/${id}/${idUser}/${line}`).pipe(map((data: any) => data));
  }

  getQuery(query: string){
    const JWT = `Bearer ${localStorage.getItem('token')}`;
    const URL = `${apiTemp}${query}`;
    return this._http.get(URL, {
      headers: new HttpHeaders({
        Authorization: JWT
      })
    });
  }

  publishAdvice(body: any){
    return this.postQuery("publish-advice", body).pipe(map((data: any) => data));
  }

  updateAdvice(body: any){
    return this.postQuery("update-advice", body).pipe(map((data: any) => data));
  }

  deleteAdvice(body: any){
    return this.postQuery("delete-advice", body).pipe(map((data: any) => data));
  }

  postQuery(query: string, body: any){
    const JWT = `Bearer ${localStorage.getItem('token')}`;
    const URL = `${apiTemp}${query}`;
    return this._http.post(URL, body, {
      headers: new HttpHeaders({
        Authorization: JWT!
      })
    });
  }
}
