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 { Publisher, PublisherDetails } from "../comic.model";

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

  loadedPublishers = this.publishers.asReadonly();

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

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

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

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