import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Papa } from 'ngx-papaparse';
import { ApiClientService } from '../../../../shared/services/api/api-client.service';
import { MercadoLiveRoute } from '../interfaces/mercado-livre.interface';

interface PaginatedResponse<T> {
  data: [{
    data_string: string;
  }];
  isFirstPage: boolean;
  isLastPage: boolean;
  nextPage: number | null;
  pageCount: number;
  previousPage: number | null;
  totalCount: number;
  currentPage: number;
}

@Injectable({
  providedIn: 'root'
})
export class MercadoLivreService {
  constructor(
    private apiClient: ApiClientService,
    private papa: Papa
  ) {
    console.log('MercadoLivreService construído');
  }

  getMercadoLiveRoutes(
    page  = 1 ,  
    limit = 100 , 
    type  = '' ,
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<MercadoLiveRoute>> {
    
    let url = `meli-route-list?page=${page}&type=${type}`;
    
    if (filters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(filters)) {
        if (value) {
          params.append(key, value);
        }
      }
      
      url += `&${params.toString()}`;
    }
    
    return this.apiClient.get<PaginatedResponse<MercadoLiveRoute>>(url);
  }

  createMercadoLiveRoute(route: Partial<MercadoLiveRoute>): Observable<MercadoLiveRoute> {
    return this.apiClient.post<MercadoLiveRoute>('meli-route-list', route);
  }

  updateMercadoLiveRoute(route: Partial<MercadoLiveRoute>): Observable<MercadoLiveRoute> {
    return this.apiClient.put<MercadoLiveRoute>(`meli-route-list/${route.id}`, route);
  }

  deleteMercadoLiveRoute(id: string): Observable<void> {
    return this.apiClient.delete<void>(`meli-route-list/${id}`);
  }

  syncMercadoLiveRoutes(): Observable<{ message: string; count: number }> {
    return this.apiClient.post<{ message: string; count: number }>('meli-route-list/sync', {});
  }
} 