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

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

  loadedSports = this.sports.asReadonly();

  loadSports() {
    return this.fetchSports('http://127.0.0.1:8800/api/tysc/sports', 'Someting went wrong fetching sports. Please try again later-');
  }

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