import { inject, Injectable, signal } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { catchError, map, throwError } from "rxjs";
import { ErrorService } from "../../../shared/error.service";
import { Artist, ArtistDetails } from "../comic.model";

@Injectable({
  providedIn: 'root',
})
export class ArtistService {
  private errorService = inject(ErrorService);
  private httpClient = inject(HttpClient);
  private artists = signal<Artist[]>([]);

  loadedArtists = this.artists.asReadonly();

  loadArtists() {
    return this.fetchArtists('http://127.0.0.1:8800/api/comics/artists', 'Someting went wrong fetching artists. Please try again later-');
  }

  loadArtistDetails(artistId: string | null) {
    return this.fetchArtistDetails('http://127.0.0.1:8800/api/comics/artists/' + artistId, 'Someting went wrong fetching comic artists. Please try again later.');
  }

  private fetchArtists(url: string, errorMessage: string) {
    return this.httpClient.get<Artist[]>(url).pipe(
      map((resData) => resData),
      catchError((error) => {
        console.log(error);
        return throwError(() => new Error(errorMessage));
      })
    );
  }

  private fetchArtistDetails(url: string, errorMessage: string) {
    return this.httpClient.get<ArtistDetails>(url).pipe(
      map((resData) => {
        console.log(resData);
        return resData;
      }),
      catchError((error) => {
        console.log(error);
        return throwError(() => new Error(errorMessage));
      })
    );
  }
}
