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

export interface ResultatCourse {
  id: number;
  course: Partial<Course>;
  statut: ResultatStatut;
  ordreArrivee: string;
  datePublication?: string; 
}

const API_BASE = '/api/v1/depouillement';

@Injectable({
  providedIn: 'root',
})
export class Depouillement {
  private apiUrl = environment.depouillementBaseUrl + API_BASE;

  constructor(private http: HttpClient) {}

  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' } : {};
  }

  /**
   * Send a resultat to the dépouillement endpoint.
   * The backend expects a payload shaped like ResultatCourse.
   */
  sendResultat(resultat: Omit<ResultatCourse, "id">): Observable<{}> {
    return this.http.post<ResultatCourse>(this.apiUrl, resultat, { headers: this.getNgrokHeaders() }).pipe(
      map((res) => res as ResultatCourse),
      catchError((err) => {
        console.error('Error sending resultat to depouillement:', err);
        return of(resultat); // return original payload on error to allow UI to proceed gracefully
      })
    );
  }
}
