import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, catchError, throwError, of } from 'rxjs';
import { environment } from '../../../environments/environment';
import { AnalysisResponse } from '../interfaces/palm-analysis.interface';

@Injectable({
  providedIn: 'root'
})
export class RemoteInferenceService {
  private readonly apiUrl = `${environment.apiUrl}/palm-oil/analyze`;

  constructor(private http: HttpClient) {}

  analyze(imageBlob: Blob): Observable<AnalysisResponse> {
    const formData = new FormData();
    // 'image' must match the @FileInterceptor('image') in NestJS
    formData.append('image', imageBlob, 'capture.jpg');

    return this.http.post<AnalysisResponse>(this.apiUrl, formData).pipe(
      catchError((error) => {
        console.error('Remote Inference Error:', error);
        return throwError(() => new Error('Remote API unreachable. Please check your connection or switch to Edge Mode.'));
      })
    );
  }

  getHistory(): Observable<any[]> {
    return this.http.get<any[]>(`${environment.apiUrl}/palm-oil/history`).pipe(
      catchError((error) => {
        console.error('Remote History Error:', error);
        return of([]);
      })
    );
  }

  deleteRecord(archiveId: string): Observable<{ deleted: boolean }> {
    return this.http.delete<{ deleted: boolean }>(
      `${environment.apiUrl}/palm-oil/history/${archiveId}`
    ).pipe(
      catchError((error) => {
        console.error('Remote delete error:', error);
        return of({ deleted: false });
      })
    );
  }

  clearAll(): Observable<{ deleted: number }> {
    return this.http.delete<{ deleted: number }>(
      `${environment.apiUrl}/palm-oil/history`
    ).pipe(
      catchError((error) => {
        console.error('Remote clear error:', error);
        return of({ deleted: 0 });
      })
    );
  }
}
