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

const USE_SERVER = true;

@Injectable({ providedIn: 'root' })
export class NonPartantService {
  constructor(private http: HttpClient) {}

  // Helper method to get ngrok bypass headers
  private getNgrokHeaders(): Record<string, string> {
    const isNgrok =
      environment.apiBaseUrl.includes('ngrok-free.app') ||
      environment.apiBaseUrl.includes('ngrok.io') ||
      environment.apiBaseUrl.includes('ngrok');
    return isNgrok ? { 'ngrok-skip-browser-warning': 'true' } : {};
  }

  // PUT /api/v1/courses/{courseId}/non-partants - Replace the list of non-partants for a course
  replaceNonPartants(courseId: string, nonPartants: NonApiRequest): Observable<CourseApiResponse | undefined> {
    const courseApiUrl = environment.apiBaseUrl + '/api/courses';
    return this.http
      .patch<CourseApiResponse>(`${courseApiUrl}/${courseId}/non-partants`, nonPartants, {
        headers: this.getNgrokHeaders(),
      })
      .pipe(
        map((res) => {
          
          return res
        }),
        catchError((err) => {
          console.log(err);
          console.error(`Error replacing non-partants for course ${courseId}:`, err);
          return of(undefined);
        })
      );
  }
}
