import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, switchMap } from 'rxjs/operators';
import { ResultatCagnotte, Formule } from '../interfaces/gain';
import { normalizePage } from '@shared/paging/normalize-page';
import { PaginatedHttpService } from '@shared/paging/paginated-http.service';
import { ListParams, PagedResult } from '@shared/paging/paging';
import { environment } from 'src/environments/environment.development';
import { ServicesUtils } from './services-utils';

const USE_SERVER = true;
const API_BASE = '/api/v1/gains';

export interface ResultatCagnotteApi extends ResultatCagnotte {}

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

  constructor(private http: HttpClient, private pager: PaginatedHttpService, private servicesUtil: 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 (paginated) ResultatCagnotte
  list(params: ListParams): Observable<PagedResult<ResultatCagnotte>> {
    if (USE_SERVER) {
      const url = this.apiUrl;
      return this.pager.fetch<ResultatCagnotteApi>(url, params).pipe(
        map((res) => {
          const content = (res.content ?? []).map((api) => api as ResultatCagnotte);
          return {
            pageable: res.pageable,
            totalPages: res.totalPages,
            totalElements: res.totalElements,
            content,
          } as PagedResult<ResultatCagnotte>;
        }),
        catchError((err) => {
          console.error('Error fetching gains list:', err);
          return of({ content: [], pageable: { pageNumber: 1, pageSize: 0, total: 0 }, totalPages: 1, totalElements: 0 } as PagedResult<ResultatCagnotte>);
        })
      );
    }

    return of({ content: [], pageable: { pageNumber: 1, pageSize: 0, total: 0 }, totalPages: 1, totalElements: 0 } as PagedResult<ResultatCagnotte>);
  }

  getById(id: string): Observable<ResultatCagnotte | undefined> {
    if (USE_SERVER) {
      return this.http.get<ResultatCagnotteApi>(`${this.apiUrl}/rapport/${id}`, { headers: this.getNgrokHeaders() }).pipe(
        map((api) => api as ResultatCagnotte),
        catchError((err) => {
          console.error(`Error fetching gain ${id}:`, err);
          return of(undefined);
        })
      );
    }
    return of(undefined);
  }

  create(payload: Partial<ResultatCagnotteApi>): Observable<ResultatCagnotte> {
    if (USE_SERVER) {
      return this.http.post<ResultatCagnotteApi>(this.apiUrl, payload, { headers: this.getNgrokHeaders() }).pipe(
        map((api) => api as ResultatCagnotte),
        catchError((err) => {
          console.error('Error creating gain:', err);
          throw err;
        })
      );
    }
    throw new Error('Server mode required');
  }

  update(id: string, payload: Partial<ResultatCagnotteApi>): Observable<ResultatCagnotte | undefined> {
    if (USE_SERVER) {
      return this.http.put<ResultatCagnotteApi>(`${this.apiUrl}/${id}`, payload, { headers: this.getNgrokHeaders() }).pipe(
        map((api) => api as ResultatCagnotte),
        catchError((err) => {
          console.error(`Error updating gain ${id}:`, err);
          return of(undefined);
        })
      );
    }
    return of(undefined);
  }

  delete(id: string): Observable<void> {
    if (USE_SERVER) {
      return this.http.delete<void>(`${this.apiUrl}/${id}`, { headers: this.getNgrokHeaders() }).pipe(
        catchError((err) => {
          console.error(`Error deleting gain ${id}:`, err);
          throw err;
        })
      );
    }
    return of(void 0);
  }
}
