import { HttpClient } from "@angular/common/http";
import { inject, Injectable, signal } from "@angular/core";
import { Comic, ComicDetails } from "../comic.model";
import { catchError, map, throwError } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class ComicService {
  private httpClient = inject(HttpClient);
  private comics = signal<Comic[]>([]);

  loadedComics = this.comics.asReadonly();

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

  loadComicDetails(comicId: string | null) {
    return this.fetchComicDetails('http://127.0.0.1:8800/api/comics/comics/' + comicId, 'Someting went wrong fetching comics. Please try again later.');
  }

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

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