import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ListParams, PagedResult } from '@shared/paging/paging';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { PointVente, PointVenteStatut } from 'src/app/core/interfaces/points-ventes';
import { environment } from 'src/environments/environment.development';
import { ServicesUtils } from './services-utils';

const API_BASE = '/api/points-de-vente';

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

  constructor(private http: HttpClient, private servicesUtils: ServicesUtils) {}

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

  list(params: ListParams): Observable<PagedResult<PointVente>> {
    return this.http
      .get<PagedResult<PointVente>>(this.apiUrl, {
        params: this.servicesUtils.getParamsFromModel(params),
        headers: this.getNgrokHeaders(),
      })
      .pipe(
        catchError((err) => {
          console.error('Error fetching points de vente:', err);
          return of({
            content: [],
            pageable: { pageNumber: 0, pageSize: params.size || 10, total: 0 },
            totalPages: 0,
            totalElements: 0,
          });
        })
      );
  }

  getById(id: string): Observable<PointVente | undefined> {
    return this.http
      .get<PointVente>(`${this.apiUrl}/${id}`, { headers: this.getNgrokHeaders() })
      .pipe(
        catchError((err) => {
          console.error(`Error fetching point de vente ${id}:`, err);
          return of(undefined);
        })
      );
  }

  create(pointVente: Omit<PointVente, 'id'>): Observable<PointVente> {
    return this.http
      .post<PointVente>(this.apiUrl, pointVente, { headers: this.getNgrokHeaders() })
      .pipe(
        catchError((err) => {
          console.log(err)
          console.error('Error creating point de vente:', err);
          throw err;
        })
      );
  }

  update(id: string, payload: Partial<PointVente>): Observable<PointVente | undefined> {
    return this.http
      .put<PointVente>(`${this.apiUrl}/${id}`, payload, { headers: this.getNgrokHeaders() })
      .pipe(
        catchError((err) => {
          console.error(`Error updating point de vente ${id}:`, err);
          return of(undefined);
        })
      );
  }

  delete(id: string): Observable<boolean> {
    return this.http
      .delete<void>(`${this.apiUrl}/${id}`, { headers: this.getNgrokHeaders() })
      .pipe(
        map(() => true),
        catchError((err) => {
          console.error(`Error deleting point de vente ${id}:`, err);
          return of(false);
        })
      );
  }
}
