import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class EventService {
  private apiUrl = environment.apiUrl+'/api/events'; // Replace with your API endpoint

  constructor(private http: HttpClient) { }

  // Fetch all events
  getEvents(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl)
      .pipe(
        catchError(this.handleError<any[]>('getEvents', []))
      );
  }

  // Fetch a single event by id
  getEvent(id: number): Observable<any> {
    const url = `${this.apiUrl}/${id}`;
    return this.http.get<any>(url)
      .pipe(
        catchError(this.handleError<any>(`getEvent id=${id}`))
      );
  }

  // Create a new event
  createEvent(event: any): Observable<any> {
    return this.http.post<any>(this.apiUrl, event, this.httpOptions)
      .pipe(
        catchError(this.handleError<any>('createEvent'))
      );
  }

  // Update an existing event
  updateEvent(id: number, event: any): Observable<any> {
    const url = `${this.apiUrl}/${id}`;
    return this.http.put<any>(url, event, this.httpOptions)
      .pipe(
        catchError(this.handleError<any>('updateEvent'))
      );
  }

  // Delete an event by id
  deleteEvent(id: number): Observable<any> {
    const url = `${this.apiUrl}/${id}`;
    return this.http.delete<any>(url)
      .pipe(
        catchError(this.handleError<any>('deleteEvent'))
      );
  }

  private httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }
}
