import { Injectable } from '@angular/core';
import { Observable, map } from 'rxjs';
import { Papa } from 'ngx-papaparse';
import { ApiClientService } from '../../shared/services/api/api-client.service';
import { Fuelcontroll } from './fuelcontroll.interface';
import { PaginatedResponse } from '../../shared/interfaces/paginate.interface';
import { DomainService } from '../../shared/components/base-domain/base-domain.component';
import { FuelControllDashBoardList } from './fuelcontroll.interface';

@Injectable({
  providedIn: 'root'
})
export class FuelcontrollService implements DomainService<Fuelcontroll> {
  
  constructor(
    private apiClient: ApiClientService,
    private papa: Papa
  ) {}

  getFuelcontrolls(
    page = 1,
    limit = 10,
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<Fuelcontroll>> {
    
    let url = `fuel-supply?page=${page}&limit=${limit}`;
    
    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<Fuelcontroll>>(url);
  }

  /**
   * Busca um fuelcontroll específico por ID
   */
  getById(id: string | number): Observable<Fuelcontroll> {
    return this.apiClient.get<Fuelcontroll>(`/fuel-supply/${id}`);
  }

  /**
   * Remove um fuelcontroll
   */
  delete(id: string | number): Observable<void> {
    return this.apiClient.delete<void>(`/fuel-supply/${id}`);
  }

  // ========================================
  // 🎯 MÉTODOS ESPERADOS PELO BaseDomainComponent
  // ========================================
  
  /**
   * ✅ Método genérico para listar - chamado automaticamente pelo BaseDomainComponent
   */
  getEntities(page: number, pageSize: number, filters: any): Observable<{
    data: Fuelcontroll[];
    totalCount: number;
    pageCount: number;
    currentPage: number;
  }> {
    return this.getFuelcontrolls(page, pageSize, filters).pipe(
      map(response => ({
        data: response.data,
        totalCount: response.totalCount,
        pageCount: response.pageCount,
        currentPage: response.currentPage
      }))
    );
  }

  /**
   * ✅ Método genérico para criar - chamado automaticamente pelo BaseDomainComponent
   */
  create(data: any): Observable<Fuelcontroll> {
    return this.apiClient.post<Fuelcontroll>('/fuel-supply', data);
  }

  /**
   * ✅ Método genérico para atualizar - chamado automaticamente pelo BaseDomainComponent
   */
  update(id: any, data: any): Observable<Fuelcontroll> {
    return this.apiClient.patch<Fuelcontroll>(`/fuel-supply/${id}`, data);
  }

  // ========================================
  // 🎯 MÉTODOS DASHBOARD
  // ========================================
  getFuelcontrollsDashboardList(
    page = 1,
    limit = 10,
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<FuelControllDashBoardList>> {
    
    let url = `fuel-supply/dashboard/list?page=${page}&limit=${limit}`;
    
    if (filters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(filters)) {
        if (value) {
          params.append(key, value);
          console.log(`🔧 [getTollparkings] Adicionando filtro: ${key} = ${value}`);
        }
      }
      
      if (params.toString()) {
        url += `&${params.toString()}`;
      }
    } 
    
    console.log(`🌐 [getTollparkings] URL final da requisição: ${url}`);
    
    return this.apiClient.get<PaginatedResponse<FuelControllDashBoardList>>(url);
  }
}